]> icculus.org git repositories - divverent/darkplaces.git/blob - zone.c
Merge branch 'master' into multicon
[divverent/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
24 #if MEMPARANOIA
25 #ifdef _MSC_VER
26 #include <vadefs.h>
27 #else
28 #include <stdint.h>
29 #endif
30 #define MEMHEADER_SENTINEL_FOR_ADDRESS(p) ((sentinel_seed ^ (unsigned int) (uintptr_t) (p)) + sentinel_seed)
31 unsigned int sentinel_seed;
32 #else
33 #define MEMHEADER_SENTINEL1 0xDEADF00D
34 #define MEMHEADER_SENTINEL2 0xDF
35 #endif
36
37 #if MEMCLUMPING
38 #define MEMCLUMP_SENTINEL 0xABADCAFE
39 #endif
40
41 cvar_t developer_memory = {0, "developer_memory", "0", "prints debugging information about memory allocations"};
42 cvar_t developer_memorydebug = {0, "developer_memorydebug", "0", "enables memory corruption checks (very slow)"};
43
44 mempool_t *poolchain = NULL;
45
46 void *_Mem_Alloc(mempool_t *pool, size_t size, const char *filename, int fileline)
47 {
48 #if MEMCLUMPING
49         int i, j, k, needed, endbit, largest;
50         memclump_t *clump, **clumpchainpointer;
51 #endif
52 #if MEMPARANOIA
53         unsigned int sentinel2;
54 #endif
55         memheader_t *mem;
56         if (size <= 0)
57                 return NULL;
58         if (pool == NULL)
59                 Sys_Error("Mem_Alloc: pool == NULL (alloc at %s:%i)", filename, fileline);
60         if (developer.integer && developer_memory.integer)
61                 Con_Printf("Mem_Alloc: pool %s, file %s:%i, size %i bytes\n", pool->name, filename, fileline, (int)size);
62         if (developer.integer && developer_memorydebug.integer)
63                 _Mem_CheckSentinelsGlobal(filename, fileline);
64         pool->totalsize += size;
65 #if MEMCLUMPING
66         if (size < 4096)
67         {
68                 // clumping
69 #if MEMPARANOIA
70                 needed = (sizeof(memheader_t) + size + sizeof(unsigned int) + (MEMUNIT - 1)) / MEMUNIT;
71 #else
72                 needed = (sizeof(memheader_t) + size + sizeof(unsigned char) + (MEMUNIT - 1)) / MEMUNIT;
73 #endif
74                 endbit = MEMBITS - needed;
75                 for (clumpchainpointer = &pool->clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
76                 {
77                         clump = *clumpchainpointer;
78                         if (clump->sentinel1 != MEMCLUMP_SENTINEL)
79                                 Sys_Error("Mem_Alloc: trashed clump sentinel 1 (alloc at %s:%d)", filename, fileline);
80                         if (clump->sentinel2 != MEMCLUMP_SENTINEL)
81                                 Sys_Error("Mem_Alloc: trashed clump sentinel 2 (alloc at %s:%d)", filename, fileline);
82                         if (clump->largestavailable >= needed)
83                         {
84                                 largest = 0;
85                                 for (i = 0;i < endbit;i++)
86                                 {
87                                         if (clump->bits[i >> 5] & (1 << (i & 31)))
88                                                 continue;
89                                         k = i + needed;
90                                         for (j = i;i < k;i++)
91                                                 if (clump->bits[i >> 5] & (1 << (i & 31)))
92                                                         goto loopcontinue;
93                                         goto choseclump;
94         loopcontinue:;
95                                         if (largest < j - i)
96                                                 largest = j - i;
97                                 }
98                                 // since clump falsely advertised enough space (nothing wrong
99                                 // with that), update largest count to avoid wasting time in
100                                 // later allocations
101                                 clump->largestavailable = largest;
102                         }
103                 }
104                 pool->realsize += sizeof(memclump_t);
105                 clump = malloc(sizeof(memclump_t));
106                 if (clump == NULL)
107                         Sys_Error("Mem_Alloc: out of memory (alloc at %s:%i)", filename, fileline);
108                 memset(clump, 0, sizeof(memclump_t));
109                 *clumpchainpointer = clump;
110                 clump->sentinel1 = MEMCLUMP_SENTINEL;
111                 clump->sentinel2 = MEMCLUMP_SENTINEL;
112                 clump->chain = NULL;
113                 clump->blocksinuse = 0;
114                 clump->largestavailable = MEMBITS - needed;
115                 j = 0;
116 choseclump:
117                 mem = (memheader_t *)((unsigned char *) clump->block + j * MEMUNIT);
118                 mem->clump = clump;
119                 clump->blocksinuse += needed;
120                 for (i = j + needed;j < i;j++)
121                         clump->bits[j >> 5] |= (1 << (j & 31));
122         }
123         else
124         {
125                 // big allocations are not clumped
126 #endif
127 #if MEMPARANOIA
128                 pool->realsize += sizeof(memheader_t) + size + sizeof(sentinel2);
129                 mem = (memheader_t *)malloc(sizeof(memheader_t) + size + sizeof(sentinel2));
130 #else
131                 pool->realsize += sizeof(memheader_t) + size + 1;
132                 mem = (memheader_t *)malloc(sizeof(memheader_t) + size + 1);
133 #endif
134                 if (mem == NULL)
135                         Sys_Error("Mem_Alloc: out of memory (alloc at %s:%i)", filename, fileline);
136 #if MEMCLUMPING
137                 mem->clump = NULL;
138         }
139 #endif
140         mem->filename = filename;
141         mem->fileline = fileline;
142         mem->size = size;
143         mem->pool = pool;
144 #if MEMPARANOIA
145         mem->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel1);
146         sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
147         memcpy((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2));
148 #else
149         mem->sentinel1 = MEMHEADER_SENTINEL1;
150         // we have to use only a single byte for this sentinel, because it may not be aligned, and some platforms can't use unaligned accesses
151         *((unsigned char *) mem + sizeof(memheader_t) + mem->size) = MEMHEADER_SENTINEL2;
152 #endif
153         // append to head of list
154         mem->next = pool->chain;
155         mem->prev = NULL;
156         pool->chain = mem;
157         if (mem->next)
158                 mem->next->prev = mem;
159         memset((void *)((unsigned char *) mem + sizeof(memheader_t)), 0, mem->size);
160         return (void *)((unsigned char *) mem + sizeof(memheader_t));
161 }
162
163 // only used by _Mem_Free and _Mem_FreePool
164 static void _Mem_FreeBlock(memheader_t *mem, const char *filename, int fileline)
165 {
166 #if MEMCLUMPING
167         int i, firstblock, endblock;
168         memclump_t *clump, **clumpchainpointer;
169 #endif
170         mempool_t *pool;
171 #if MEMPARANOIA
172         unsigned int sentinel2;
173         if (mem->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel1))
174                 Sys_Error("Mem_Free: trashed header sentinel 1 (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
175         sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
176         if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
177                 Sys_Error("Mem_Free: trashed header sentinel 2 (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
178 #else
179         if (mem->sentinel1 != MEMHEADER_SENTINEL1)
180                 Sys_Error("Mem_Free: trashed header sentinel 1 (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
181         if (*((unsigned char *) mem + sizeof(memheader_t) + mem->size) != MEMHEADER_SENTINEL2)
182                 Sys_Error("Mem_Free: trashed header sentinel 2 (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
183 #endif
184         pool = mem->pool;
185         if (developer.integer && developer_memory.integer)
186                 Con_Printf("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));
187         // unlink memheader from doubly linked list
188         if ((mem->prev ? mem->prev->next != mem : pool->chain != mem) || (mem->next && mem->next->prev != mem))
189                 Sys_Error("Mem_Free: not allocated or double freed (free at %s:%i)", filename, fileline);
190         if (mem->prev)
191                 mem->prev->next = mem->next;
192         else
193                 pool->chain = mem->next;
194         if (mem->next)
195                 mem->next->prev = mem->prev;
196         // memheader has been unlinked, do the actual free now
197         pool->totalsize -= mem->size;
198 #if MEMCLUMPING
199         if ((clump = mem->clump))
200         {
201                 if (clump->sentinel1 != MEMCLUMP_SENTINEL)
202                         Sys_Error("Mem_Free: trashed clump sentinel 1 (free at %s:%i)", filename, fileline);
203                 if (clump->sentinel2 != MEMCLUMP_SENTINEL)
204                         Sys_Error("Mem_Free: trashed clump sentinel 2 (free at %s:%i)", filename, fileline);
205                 firstblock = ((unsigned char *) mem - (unsigned char *) clump->block);
206                 if (firstblock & (MEMUNIT - 1))
207                         Sys_Error("Mem_Free: address not valid in clump (free at %s:%i)", filename, fileline);
208                 firstblock /= MEMUNIT;
209                 endblock = firstblock + ((sizeof(memheader_t) + mem->size + sizeof(int) + (MEMUNIT - 1)) / MEMUNIT);
210                 clump->blocksinuse -= endblock - firstblock;
211                 // could use &, but we know the bit is set
212                 for (i = firstblock;i < endblock;i++)
213                         clump->bits[i >> 5] -= (1 << (i & 31));
214                 if (clump->blocksinuse <= 0)
215                 {
216                         // unlink from chain
217                         for (clumpchainpointer = &pool->clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
218                         {
219                                 if (*clumpchainpointer == clump)
220                                 {
221                                         *clumpchainpointer = clump->chain;
222                                         break;
223                                 }
224                         }
225                         pool->realsize -= sizeof(memclump_t);
226                         memset(clump, 0xBF, sizeof(memclump_t));
227                         free(clump);
228                 }
229                 else
230                 {
231                         // clump still has some allocations
232                         // force re-check of largest available space on next alloc
233                         clump->largestavailable = MEMBITS - clump->blocksinuse;
234                 }
235         }
236         else
237         {
238 #endif
239                 pool->realsize -= sizeof(memheader_t) + mem->size + sizeof(int);
240                 if (developer_memorydebug.integer)
241                         memset(mem, 0xBF, sizeof(memheader_t) + mem->size + sizeof(int));
242                 free(mem);
243 #if MEMCLUMPING
244         }
245 #endif
246 }
247
248 void _Mem_Free(void *data, const char *filename, int fileline)
249 {
250         if (data == NULL)
251         {
252                 Con_DPrintf("Mem_Free: data == NULL (called at %s:%i)\n", filename, fileline);
253                 return;
254         }
255
256         if (developer.integer && developer_memorydebug.integer)
257         {
258                 _Mem_CheckSentinelsGlobal(filename, fileline);
259                 if (!Mem_IsAllocated(NULL, data))
260                         Sys_Error("Mem_Free: data is not allocated (called at %s:%i)", filename, fileline);
261         }
262
263         _Mem_FreeBlock((memheader_t *)((unsigned char *) data - sizeof(memheader_t)), filename, fileline);
264 }
265
266 mempool_t *_Mem_AllocPool(const char *name, int flags, mempool_t *parent, const char *filename, int fileline)
267 {
268         mempool_t *pool;
269         if (developer.integer && developer_memorydebug.integer)
270                 _Mem_CheckSentinelsGlobal(filename, fileline);
271         pool = (mempool_t *)malloc(sizeof(mempool_t));
272         if (pool == NULL)
273                 Sys_Error("Mem_AllocPool: out of memory (allocpool at %s:%i)", filename, fileline);
274         memset(pool, 0, sizeof(mempool_t));
275 #if MEMPARANOIA
276         pool->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1);
277         pool->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2);
278 #else
279         pool->sentinel1 = MEMHEADER_SENTINEL1;
280         pool->sentinel2 = MEMHEADER_SENTINEL1;
281 #endif
282         pool->filename = filename;
283         pool->fileline = fileline;
284         pool->flags = flags;
285         pool->chain = NULL;
286         pool->totalsize = 0;
287         pool->realsize = sizeof(mempool_t);
288         strlcpy (pool->name, name, sizeof (pool->name));
289         pool->parent = parent;
290         pool->next = poolchain;
291         poolchain = pool;
292         return pool;
293 }
294
295 void _Mem_FreePool(mempool_t **poolpointer, const char *filename, int fileline)
296 {
297         mempool_t *pool = *poolpointer;
298         mempool_t **chainaddress, *iter, *temp;
299
300         if (developer.integer && developer_memorydebug.integer)
301                 _Mem_CheckSentinelsGlobal(filename, fileline);
302         if (pool)
303         {
304                 // unlink pool from chain
305                 for (chainaddress = &poolchain;*chainaddress && *chainaddress != pool;chainaddress = &((*chainaddress)->next));
306                 if (*chainaddress != pool)
307                         Sys_Error("Mem_FreePool: pool already free (freepool at %s:%i)", filename, fileline);
308 #if MEMPARANOIA
309                 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
310                         Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
311                 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
312                         Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
313 #else
314                 if (pool->sentinel1 != MEMHEADER_SENTINEL1)
315                         Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
316                 if (pool->sentinel2 != MEMHEADER_SENTINEL1)
317                         Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
318 #endif
319                 *chainaddress = pool->next;
320
321                 // free memory owned by the pool
322                 while (pool->chain)
323                         _Mem_FreeBlock(pool->chain, filename, fileline);
324
325                 // free child pools, too
326                 for(iter = poolchain; iter; temp = iter = iter->next)
327                         if(iter->parent == pool)
328                                 _Mem_FreePool(&temp, filename, fileline);
329
330                 // free the pool itself
331                 memset(pool, 0xBF, sizeof(mempool_t));
332                 free(pool);
333
334                 *poolpointer = NULL;
335         }
336 }
337
338 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
339 {
340         mempool_t *chainaddress;
341
342         if (developer.integer && developer_memorydebug.integer)
343         {
344                 _Mem_CheckSentinelsGlobal(filename, fileline);
345                 // check if this pool is in the poolchain
346                 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
347                         if (chainaddress == pool)
348                                 break;
349                 if (!chainaddress)
350                         Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
351         }
352         if (pool == NULL)
353                 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
354 #if MEMPARANOIA
355         if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
356                 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
357         if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
358                 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
359 #else
360         if (pool->sentinel1 != MEMHEADER_SENTINEL1)
361                 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
362         if (pool->sentinel2 != MEMHEADER_SENTINEL1)
363                 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
364 #endif
365
366         // free memory owned by the pool
367         while (pool->chain)
368                 _Mem_FreeBlock(pool->chain, filename, fileline);
369
370         // empty child pools, too
371         for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
372                 if(chainaddress->parent == pool)
373                         _Mem_EmptyPool(chainaddress, filename, fileline);
374
375 }
376
377 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
378 {
379         memheader_t *mem;
380 #if MEMPARANOIA
381         unsigned int sentinel2;
382 #endif
383
384         if (data == NULL)
385                 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
386
387         mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
388 #if MEMPARANOIA
389         if (mem->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel1))
390                 Sys_Error("Mem_Free: trashed header sentinel 1 (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
391         sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
392         if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
393                 Sys_Error("Mem_Free: trashed header sentinel 2 (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
394 #else
395         if (mem->sentinel1 != MEMHEADER_SENTINEL1)
396                 Sys_Error("Mem_CheckSentinels: trashed header sentinel 1 (block allocated at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
397         if (*((unsigned char *) mem + sizeof(memheader_t) + mem->size) != MEMHEADER_SENTINEL2)
398                 Sys_Error("Mem_CheckSentinels: trashed header sentinel 2 (block allocated at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
399 #endif
400 }
401
402 #if MEMCLUMPING
403 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
404 {
405         // this isn't really very useful
406         if (clump->sentinel1 != MEMCLUMP_SENTINEL)
407                 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
408         if (clump->sentinel2 != MEMCLUMP_SENTINEL)
409                 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
410 }
411 #endif
412
413 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
414 {
415         memheader_t *mem;
416 #if MEMCLUMPING
417         memclump_t *clump;
418 #endif
419         mempool_t *pool;
420         for (pool = poolchain;pool;pool = pool->next)
421         {
422 #if MEMPARANOIA
423                 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
424                         Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
425                 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
426                         Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
427 #else
428                 if (pool->sentinel1 != MEMHEADER_SENTINEL1)
429                         Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
430                 if (pool->sentinel2 != MEMHEADER_SENTINEL1)
431                         Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
432 #endif
433         }
434         for (pool = poolchain;pool;pool = pool->next)
435                 for (mem = pool->chain;mem;mem = mem->next)
436                         _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
437 #if MEMCLUMPING
438         for (pool = poolchain;pool;pool = pool->next)
439                 for (clump = pool->clumpchain;clump;clump = clump->chain)
440                         _Mem_CheckClumpSentinels(clump, filename, fileline);
441 #endif
442 }
443
444 qboolean Mem_IsAllocated(mempool_t *pool, void *data)
445 {
446         memheader_t *header;
447         memheader_t *target;
448
449         if (pool)
450         {
451                 // search only one pool
452                 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
453                 for( header = pool->chain ; header ; header = header->next )
454                         if( header == target )
455                                 return true;
456         }
457         else
458         {
459                 // search all pools
460                 for (pool = poolchain;pool;pool = pool->next)
461                         if (Mem_IsAllocated(pool, data))
462                                 return true;
463         }
464         return false;
465 }
466
467 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
468 {
469         memset(l, 0, sizeof(*l));
470         l->mempool = mempool;
471         l->recordsize = recordsize;
472         l->numrecordsperarray = numrecordsperarray;
473 }
474
475 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
476 {
477         size_t i;
478         if (l->maxarrays)
479         {
480                 for (i = 0;i != l->numarrays;i++)
481                         Mem_Free(l->arrays[i].data);
482                 Mem_Free(l->arrays);
483         }
484         memset(l, 0, sizeof(*l));
485 }
486
487 void *Mem_ExpandableArray_AllocRecord_Id(memexpandablearray_t *l, size_t *out_id)
488 {
489         size_t i, j;
490         for (i = 0;;i++)
491         {
492                 if (i == l->numarrays)
493                 {
494                         if (l->numarrays == l->maxarrays)
495                         {
496                                 memexpandablearray_array_t *oldarrays = l->arrays;
497                                 l->maxarrays = max(l->maxarrays * 2, 128);
498                                 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
499                                 if (oldarrays)
500                                 {
501                                         memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
502                                         Mem_Free(oldarrays);
503                                 }
504                         }
505                         l->arrays[i].numflaggedrecords = 0;
506                         l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
507                         l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
508                         l->numarrays++;
509                 }
510                 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
511                 {
512                         for (j = 0;j < l->numrecordsperarray;j++)
513                         {
514                                 if (!l->arrays[i].allocflags[j])
515                                 {
516                                         l->arrays[i].allocflags[j] = true;
517                                         l->arrays[i].numflaggedrecords++;
518                                         memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
519                                         if (out_id)
520                                                 *out_id = i * l->numrecordsperarray + j;
521                                         return (void *)(l->arrays[i].data + l->recordsize * j);
522                                 }
523                         }
524                 }
525         }
526 }
527
528 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
529 {
530         return Mem_ExpandableArray_AllocRecord_Id(l, NULL);
531 }
532
533 /*****************************************************************************
534  * IF YOU EDIT THIS:
535  * If this function was to change the size of the "expandable" array, you have
536  * to update r_shadow.c
537  * Just do a search for "range =", R_ShadowClearWorldLights would be the first
538  * function to look at. (And also seems like the only one?) You  might have to
539  * move the  call to Mem_ExpandableArray_IndexRange  back into for(...) loop's
540  * condition
541  */
542 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
543 {
544         size_t i, j;
545         unsigned char *p = (unsigned char *)record;
546         for (i = 0;i != l->numarrays;i++)
547         {
548                 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
549                 {
550                         j = (p - l->arrays[i].data) / l->recordsize;
551                         if (p != l->arrays[i].data + j * l->recordsize)
552                                 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", p);
553                         if (!l->arrays[i].allocflags[j])
554                                 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", p);
555                         l->arrays[i].allocflags[j] = false;
556                         l->arrays[i].numflaggedrecords--;
557                         return;
558                 }
559         }
560 }
561
562 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
563 {
564         size_t i, j, k, end = 0;
565         for (i = 0;i < l->numarrays;i++)
566         {
567                 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
568                 {
569                         if (l->arrays[i].allocflags[j])
570                         {
571                                 end = l->numrecordsperarray * i + j + 1;
572                                 k++;
573                         }
574                 }
575         }
576         return end;
577 }
578
579 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
580 {
581         size_t i, j;
582         i = index / l->numrecordsperarray;
583         j = index % l->numrecordsperarray;
584         if (i >= l->numarrays || !l->arrays[i].allocflags[j])
585                 return NULL;
586         return (void *)(l->arrays[i].data + j * l->recordsize);
587 }
588
589
590 // used for temporary memory allocations around the engine, not for longterm
591 // storage, if anything in this pool stays allocated during gameplay, it is
592 // considered a leak
593 mempool_t *tempmempool;
594 // only for zone
595 mempool_t *zonemempool;
596
597 void Mem_PrintStats(void)
598 {
599         size_t count = 0, size = 0, realsize = 0;
600         mempool_t *pool;
601         memheader_t *mem;
602         Mem_CheckSentinelsGlobal();
603         for (pool = poolchain;pool;pool = pool->next)
604         {
605                 count++;
606                 size += pool->totalsize;
607                 realsize += pool->realsize;
608         }
609         Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
610         Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
611         for (pool = poolchain;pool;pool = pool->next)
612         {
613                 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
614                 {
615                         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);
616                         for (mem = pool->chain;mem;mem = mem->next)
617                                 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
618                 }
619         }
620 }
621
622 void Mem_PrintList(size_t minallocationsize)
623 {
624         mempool_t *pool;
625         memheader_t *mem;
626         Mem_CheckSentinelsGlobal();
627         Con_Print("memory pool list:\n"
628                    "size    name\n");
629         for (pool = poolchain;pool;pool = pool->next)
630         {
631                 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" : "");
632                 pool->lastchecksize = pool->totalsize;
633                 for (mem = pool->chain;mem;mem = mem->next)
634                         if (mem->size >= minallocationsize)
635                                 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
636         }
637 }
638
639 void MemList_f(void)
640 {
641         switch(Cmd_Argc())
642         {
643         case 1:
644                 Mem_PrintList(1<<30);
645                 Mem_PrintStats();
646                 break;
647         case 2:
648                 Mem_PrintList(atoi(Cmd_Argv(1)) * 1024);
649                 Mem_PrintStats();
650                 break;
651         default:
652                 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
653                 break;
654         }
655 }
656
657 extern void R_TextureStats_Print(qboolean printeach, qboolean printpool, qboolean printtotal);
658 void MemStats_f(void)
659 {
660         Mem_CheckSentinelsGlobal();
661         R_TextureStats_Print(false, false, true);
662         GL_Mesh_ListVBOs(false);
663         Mem_PrintStats();
664 }
665
666
667 char* Mem_strdup (mempool_t *pool, const char* s)
668 {
669         char* p;
670         size_t sz = strlen (s) + 1;
671         if (s == NULL) return NULL;
672         p = (char*)Mem_Alloc (pool, sz);
673         strlcpy (p, s, sz);
674         return p;
675 }
676
677 /*
678 ========================
679 Memory_Init
680 ========================
681 */
682 void Memory_Init (void)
683 {
684 #if MEMPARANOIA
685         sentinel_seed = rand();
686 #endif
687         poolchain = NULL;
688         tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
689         zonemempool = Mem_AllocPool("Zone", 0, NULL);
690 }
691
692 void Memory_Shutdown (void)
693 {
694 //      Mem_FreePool (&zonemempool);
695 //      Mem_FreePool (&tempmempool);
696 }
697
698 void Memory_Init_Commands (void)
699 {
700         Cmd_AddCommand ("memstats", MemStats_f, "prints memory system statistics");
701         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)");
702         Cvar_RegisterVariable (&developer_memory);
703         Cvar_RegisterVariable (&developer_memorydebug);
704 }
705