3 * ***** BEGIN GPL LICENSE BLOCK *****
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
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 Foundation,
17 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20 * All rights reserved.
22 * The Original Code is: all of this file.
24 * Contributor(s): none yet.
26 * ***** END GPL LICENSE BLOCK *****
32 * Copyright (C) 2001 NaN Technologies B.V.
33 * Guarded memory allocation, and boundary-write detection.
37 #include <string.h> /* memcpy */
42 #include <sys/types.h>
45 #include <sys/types.h>
49 #include "MEM_guardedalloc.h"
51 /* Only for debugging:
52 * lets you count the allocations so as to find the allocator of unfreed memory
53 * in situations where the leak is pradictable */
55 // #define DEBUG_MEMCOUNTER
57 #ifdef DEBUG_MEMCOUNTER
58 #define DEBUG_MEMCOUNTER_ERROR_VAL 0 /* set this to the value that isnt being freed */
59 static int _mallocn_count = 0;
62 static void memcount_raise(const char *name)
64 fprintf(stderr, "%s: memcount-leak, %d\n", name, _mallocn_count);
68 /* --------------------------------------------------------------------- */
70 /* --------------------------------------------------------------------- */
71 /* all memory chunks are put in linked lists */
72 typedef struct localLink
74 struct localLink *next,*prev;
77 typedef struct localListBase
82 /* note: keep this struct aligned (e.g., irix/gcc) - Hos */
83 typedef struct MemHead {
86 struct MemHead *next,*prev;
88 const char * nextname;
90 int mmap; /* if true, memory was mmapped */
91 #ifdef DEBUG_MEMCOUNTER
96 typedef struct MemTail {
101 /* --------------------------------------------------------------------- */
102 /* local functions */
103 /* --------------------------------------------------------------------- */
105 static void addtail(volatile localListBase *listbase, void *vlink);
106 static void remlink(volatile localListBase *listbase, void *vlink);
107 static void rem_memblock(MemHead *memh);
108 static void MemorY_ErroR(const char *block, const char *error);
109 static const char *check_memlist(MemHead *memh);
111 /* --------------------------------------------------------------------- */
112 /* locally used defines */
113 /* --------------------------------------------------------------------- */
115 #if defined( __sgi) || defined (__sun) || defined (__sun__) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || (defined (__APPLE__) && !defined(__LITTLE_ENDIAN__))
116 #define MAKE_ID(a,b,c,d) ( (int)(a)<<24 | (int)(b)<<16 | (c)<<8 | (d) )
118 #define MAKE_ID(a,b,c,d) ( (int)(d)<<24 | (int)(c)<<16 | (b)<<8 | (a) )
121 #define MEMTAG1 MAKE_ID('M', 'E', 'M', 'O')
122 #define MEMTAG2 MAKE_ID('R', 'Y', 'B', 'L')
123 #define MEMTAG3 MAKE_ID('O', 'C', 'K', '!')
124 #define MEMFREE MAKE_ID('F', 'R', 'E', 'E')
126 #define MEMNEXT(x) ((MemHead *)(((char *) x) - ((char *) & (((MemHead *)0)->next))))
128 /* --------------------------------------------------------------------- */
130 /* --------------------------------------------------------------------- */
133 static volatile int totblock= 0;
134 static volatile uintptr_t mem_in_use= 0, mmap_in_use= 0;
136 static volatile struct localListBase _membase;
137 static volatile struct localListBase *membase = &_membase;
138 static void (*error_callback)(const char *) = NULL;
139 static void (*thread_lock_callback)(void) = NULL;
140 static void (*thread_unlock_callback)(void) = NULL;
142 static int malloc_debug_memset= 0;
157 /* --------------------------------------------------------------------- */
159 /* --------------------------------------------------------------------- */
161 static void print_error(const char *str, ...)
167 vsprintf(buf, str, ap);
170 if (error_callback) error_callback(buf);
173 static void mem_lock_thread()
175 if (thread_lock_callback)
176 thread_lock_callback();
179 static void mem_unlock_thread()
181 if (thread_unlock_callback)
182 thread_unlock_callback();
185 int MEM_check_memory_integrity()
187 const char* err_val = NULL;
189 /* check_memlist starts from the front, and runs until it finds
190 * the requested chunk. For this test, that's the last one. */
191 listend = membase->last;
193 err_val = check_memlist(listend);
195 if (err_val == 0) return 0;
200 void MEM_set_error_callback(void (*func)(const char *))
202 error_callback = func;
205 void MEM_set_lock_callback(void (*lock)(void), void (*unlock)(void))
207 thread_lock_callback = lock;
208 thread_unlock_callback = unlock;
211 void MEM_set_memory_debug(void)
213 malloc_debug_memset= 1;
216 int MEM_allocN_len(void *vmemh)
219 MemHead *memh= vmemh;
227 void *MEM_dupallocN(void *vmemh)
232 MemHead *memh= vmemh;
236 newp= MEM_mapallocN(memh->len, "dupli_mapalloc");
238 newp= MEM_mallocN(memh->len, "dupli_alloc");
240 if (newp == NULL) return NULL;
242 memcpy(newp, vmemh, memh->len);
248 void *MEM_reallocN(void *vmemh, unsigned int len)
253 MemHead *memh= vmemh;
256 newp= MEM_mallocN(len, memh->name);
259 memcpy(newp, vmemh, len);
261 memcpy(newp, vmemh, memh->len);
270 static void make_memhead_header(MemHead *memh, unsigned int len, const char *str)
274 memh->tag1 = MEMTAG1;
279 memh->tag2 = MEMTAG2;
281 memt = (MemTail *)(((char *) memh) + sizeof(MemHead) + len);
282 memt->tag3 = MEMTAG3;
284 addtail(membase,&memh->next);
285 if (memh->next) memh->nextname = MEMNEXT(memh->next)->name;
291 void *MEM_mallocN(unsigned int len, const char *str)
297 len = (len + 3 ) & ~3; /* allocate in units of 4 */
299 memh= (MemHead *)malloc(len+sizeof(MemHead)+sizeof(MemTail));
302 make_memhead_header(memh, len, str);
304 if(malloc_debug_memset && len)
305 memset(memh+1, 255, len);
307 #ifdef DEBUG_MEMCOUNTER
308 if(_mallocn_count==DEBUG_MEMCOUNTER_ERROR_VAL)
309 memcount_raise("MEM_mallocN");
310 memh->_count= _mallocn_count++;
315 print_error("Malloc returns nill: len=%d in %s, total %u\n",len, str, mem_in_use);
319 void *MEM_callocN(unsigned int len, const char *str)
325 len = (len + 3 ) & ~3; /* allocate in units of 4 */
327 memh= (MemHead *)calloc(len+sizeof(MemHead)+sizeof(MemTail),1);
330 make_memhead_header(memh, len, str);
332 #ifdef DEBUG_MEMCOUNTER
333 if(_mallocn_count==DEBUG_MEMCOUNTER_ERROR_VAL)
334 memcount_raise("MEM_callocN");
335 memh->_count= _mallocn_count++;
340 print_error("Calloc returns nill: len=%d in %s, total %u\n",len, str, mem_in_use);
344 /* note; mmap returns zero'd memory */
345 void *MEM_mapallocN(unsigned int len, const char *str)
351 len = (len + 3 ) & ~3; /* allocate in units of 4 */
358 fd = open("/dev/zero", O_RDWR);
360 memh= mmap(0, len+sizeof(MemHead)+sizeof(MemTail),
361 PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
365 memh= mmap(0, len+sizeof(MemHead)+sizeof(MemTail),
366 PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0);
369 if(memh!=(MemHead *)-1) {
370 make_memhead_header(memh, len, str);
374 #ifdef DEBUG_MEMCOUNTER
375 if(_mallocn_count==DEBUG_MEMCOUNTER_ERROR_VAL)
376 memcount_raise("MEM_mapallocN");
377 memh->_count= _mallocn_count++;
383 print_error("Mapalloc returns nill, fallback to regular malloc: len=%d in %s, total %u\n",len, str, mmap_in_use);
384 return MEM_callocN(len, str);
388 /* Memory statistics print */
389 typedef struct MemPrintBlock {
395 static int compare_name(const void *p1, const void *p2)
397 const MemPrintBlock *pb1= (const MemPrintBlock*)p1;
398 const MemPrintBlock *pb2= (const MemPrintBlock*)p2;
400 return strcmp(pb1->name, pb2->name);
403 static int compare_len(const void *p1, const void *p2)
405 const MemPrintBlock *pb1= (const MemPrintBlock*)p1;
406 const MemPrintBlock *pb2= (const MemPrintBlock*)p2;
408 if(pb1->len < pb2->len)
410 else if(pb1->len == pb2->len)
416 void MEM_printmemlist_stats()
419 MemPrintBlock *pb, *printblock;
424 /* put memory blocks into array */
425 printblock= malloc(sizeof(MemPrintBlock)*totblock);
430 membl = membase->first;
431 if (membl) membl = MEMNEXT(membl);
434 pb->name= membl->name;
442 membl= MEMNEXT(membl->next);
446 /* sort by name and add together blocks with the same name */
447 qsort(printblock, totpb, sizeof(MemPrintBlock), compare_name);
448 for(a=0, b=0; a<totpb; a++) {
452 else if(strcmp(printblock[a].name, printblock[b].name) == 0) {
453 printblock[b].len += printblock[a].len;
454 printblock[b].items++;
458 memcpy(&printblock[b], &printblock[a], sizeof(MemPrintBlock));
463 /* sort by length and print */
464 qsort(printblock, totpb, sizeof(MemPrintBlock), compare_len);
465 printf("\ntotal memory len: %.3f MB\n", (double)mem_in_use/(double)(1024*1024));
466 for(a=0, pb=printblock; a<totpb; a++, pb++)
467 printf("%s items: %d, len: %.3f MB\n", pb->name, pb->items, (double)pb->len/(double)(1024*1024));
474 /* Prints in python syntax for easy */
475 static void MEM_printmemlist_internal( int pydict )
481 membl = membase->first;
482 if (membl) membl = MEMNEXT(membl);
485 print_error("# membase_debug.py\n");
486 print_error("membase = [\\\n");
490 fprintf(stderr, "{'len':%i, 'name':'''%s''', 'pointer':'%p'},\\\n", membl->len, membl->name, membl+1);
492 #ifdef DEBUG_MEMCOUNTER
493 print_error("%s len: %d %p, count: %d\n",membl->name,membl->len, membl+1, membl->_count);
495 print_error("%s len: %d %p\n",membl->name,membl->len, membl+1);
499 membl= MEMNEXT(membl->next);
503 fprintf(stderr, "]\n\n");
507 "for mb_item in membase:\n"
508 "\tmb_item_user_size = mb_userinfo.setdefault(mb_item['name'], [0,0])\n"
509 "\tmb_item_user_size[0] += 1 # Add a user\n"
510 "\tmb_item_user_size[1] += mb_item['len'] # Increment the size\n"
511 "\ttotmem += mb_item['len']\n"
512 "print '(membase) items:', len(membase), '| unique-names:', len(mb_userinfo), '| total-mem:', totmem\n"
513 "mb_userinfo_sort = mb_userinfo.items()\n"
514 "for sort_name, sort_func in (('size', lambda a: -a[1][1]), ('users', lambda a: -a[1][0]), ('name', lambda a: a[0])):\n"
515 "\tprint '\\nSorting by:', sort_name\n"
516 "\tmb_userinfo_sort.sort(key = sort_func)\n"
517 "\tfor item in mb_userinfo_sort:\n"
518 "\t\tprint 'name:%%s, users:%%i, len:%%i' %% (item[0], item[1][0], item[1][1])\n"
525 void MEM_callbackmemlist(void (*func)(void*)) {
530 membl = membase->first;
531 if (membl) membl = MEMNEXT(membl);
536 membl= MEMNEXT(membl->next);
543 short MEM_testN(void *vmemh) {
548 membl = membase->first;
549 if (membl) membl = MEMNEXT(membl);
552 if (vmemh == membl+1) {
558 membl= MEMNEXT(membl->next);
564 print_error("Memoryblock %p: pointer not in memlist\n", vmemh);
568 void MEM_printmemlist( void ) {
569 MEM_printmemlist_internal(0);
571 void MEM_printmemlist_pydict( void ) {
572 MEM_printmemlist_internal(1);
575 short MEM_freeN(void *vmemh) /* anders compileertie niet meer */
579 MemHead *memh= vmemh;
583 MemorY_ErroR("free","attempt to free NULL pointer");
584 /* print_error(err_stream, "%d\n", (memh+4000)->tag1); */
588 if(sizeof(intptr_t)==8) {
589 if (((intptr_t) memh) & 0x7) {
590 MemorY_ErroR("free","attempt to free illegal pointer");
595 if (((intptr_t) memh) & 0x3) {
596 MemorY_ErroR("free","attempt to free illegal pointer");
602 if(memh->tag1 == MEMFREE && memh->tag2 == MEMFREE) {
603 MemorY_ErroR(memh->name,"double free");
608 if ((memh->tag1 == MEMTAG1) && (memh->tag2 == MEMTAG2) && ((memh->len & 0x3) == 0)) {
609 memt = (MemTail *)(((char *) memh) + sizeof(MemHead) + memh->len);
610 if (memt->tag3 == MEMTAG3){
612 memh->tag1 = MEMFREE;
613 memh->tag2 = MEMFREE;
614 memt->tag3 = MEMFREE;
623 MemorY_ErroR(memh->name,"end corrupt");
624 name = check_memlist(memh);
626 if (name != memh->name) MemorY_ErroR(name,"is also corrupt");
630 name = check_memlist(memh);
632 MemorY_ErroR("free","pointer not in memlist");
634 MemorY_ErroR(name,"error in header");
638 /* here a DUMP should happen */
645 /* --------------------------------------------------------------------- */
646 /* local functions */
647 /* --------------------------------------------------------------------- */
649 static void addtail(volatile localListBase *listbase, void *vlink)
651 struct localLink *link= vlink;
653 if (link == 0) return;
654 if (listbase == 0) return;
657 link->prev = listbase->last;
659 if (listbase->last) ((struct localLink *)listbase->last)->next = link;
660 if (listbase->first == 0) listbase->first = link;
661 listbase->last = link;
664 static void remlink(volatile localListBase *listbase, void *vlink)
666 struct localLink *link= vlink;
668 if (link == 0) return;
669 if (listbase == 0) return;
671 if (link->next) link->next->prev = link->prev;
672 if (link->prev) link->prev->next = link->next;
674 if (listbase->last == link) listbase->last = link->prev;
675 if (listbase->first == link) listbase->first = link->next;
678 static void rem_memblock(MemHead *memh)
680 remlink(membase,&memh->next);
683 MEMNEXT(memh->prev)->nextname = MEMNEXT(memh->next)->name;
685 MEMNEXT(memh->prev)->nextname = NULL;
689 mem_in_use -= memh->len;
692 mmap_in_use -= memh->len;
693 if (munmap(memh, memh->len + sizeof(MemHead) + sizeof(MemTail)))
694 printf("Couldn't unmap memory %s\n", memh->name);
697 if(malloc_debug_memset && memh->len)
698 memset(memh+1, 255, memh->len);
703 static void MemorY_ErroR(const char *block, const char *error)
705 print_error("Memoryblock %s: %s\n",block, error);
708 static const char *check_memlist(MemHead *memh)
710 MemHead *forw,*back,*forwok,*backok;
713 forw = membase->first;
714 if (forw) forw = MEMNEXT(forw);
717 if (forw->tag1 != MEMTAG1 || forw->tag2 != MEMTAG2) break;
719 if (forw->next) forw = MEMNEXT(forw->next);
723 back = (MemHead *) membase->last;
724 if (back) back = MEMNEXT(back);
727 if (back->tag1 != MEMTAG1 || back->tag2 != MEMTAG2) break;
729 if (back->prev) back = MEMNEXT(back->prev);
733 if (forw != back) return ("MORE THAN 1 MEMORYBLOCK CORRUPT");
735 if (forw == 0 && back == 0){
736 /* geen foute headers gevonden dan maar op zoek naar memblock*/
738 forw = membase->first;
739 if (forw) forw = MEMNEXT(forw);
742 if (forw == memh) break;
743 if (forw->tag1 != MEMTAG1 || forw->tag2 != MEMTAG2) break;
745 if (forw->next) forw = MEMNEXT(forw->next);
748 if (forw == 0) return (0);
750 back = (MemHead *) membase->last;
751 if (back) back = MEMNEXT(back);
754 if (back == memh) break;
755 if (back->tag1 != MEMTAG1 || back->tag2 != MEMTAG2) break;
757 if (back->prev) back = MEMNEXT(back->prev);
762 if (forwok) name = forwok->nextname;
763 else name = "No name found";
766 /* voor alle zekerheid wordt dit block maar uit de lijst gehaald */
769 forwok->next = (MemHead *)&backok->next;
770 backok->prev = (MemHead *)&forwok->next;
771 forwok->nextname = backok->name;
774 membase->last = (struct localLink *) &forwok->next;
775 /* membase->last = (struct Link *) &forwok->next; */
780 membase->first = &backok->next;
782 membase->first = membase->last = 0;
786 MemorY_ErroR(name,"Additional error in header");
787 return("Additional error in header");
793 uintptr_t MEM_get_memory_in_use(void)
795 uintptr_t _mem_in_use;
798 _mem_in_use= mem_in_use;
804 uintptr_t MEM_get_mapped_memory_in_use(void)
806 uintptr_t _mmap_in_use;
809 _mmap_in_use= mmap_in_use;
815 int MEM_get_memory_blocks_in_use(void)