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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 /* --------------------------------------------------------------------- */
53 /* --------------------------------------------------------------------- */
54 /* all memory chunks are put in linked lists */
55 typedef struct localLink
57 struct localLink *next,*prev;
60 typedef struct localListBase
65 /* note: keep this struct aligned (e.g., irix/gcc) - Hos */
66 typedef struct MemHead {
69 struct MemHead *next,*prev;
71 const char * nextname;
73 int mmap; /* if true, memory was mmapped */
76 typedef struct MemTail {
81 /* --------------------------------------------------------------------- */
83 /* --------------------------------------------------------------------- */
85 static void addtail(volatile localListBase *listbase, void *vlink);
86 static void remlink(volatile localListBase *listbase, void *vlink);
87 static void rem_memblock(MemHead *memh);
88 static void MemorY_ErroR(const char *block, const char *error);
89 static const char *check_memlist(MemHead *memh);
91 /* --------------------------------------------------------------------- */
92 /* locally used defines */
93 /* --------------------------------------------------------------------- */
95 #if defined( __sgi) || defined (__sun) || defined (__sun__) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || (defined (__APPLE__) && !defined(__LITTLE_ENDIAN__))
96 #define MAKE_ID(a,b,c,d) ( (int)(a)<<24 | (int)(b)<<16 | (c)<<8 | (d) )
98 #define MAKE_ID(a,b,c,d) ( (int)(d)<<24 | (int)(c)<<16 | (b)<<8 | (a) )
101 #define MEMTAG1 MAKE_ID('M', 'E', 'M', 'O')
102 #define MEMTAG2 MAKE_ID('R', 'Y', 'B', 'L')
103 #define MEMTAG3 MAKE_ID('O', 'C', 'K', '!')
104 #define MEMFREE MAKE_ID('F', 'R', 'E', 'E')
106 #define MEMNEXT(x) ((MemHead *)(((char *) x) - ((char *) & (((MemHead *)0)->next))))
108 /* --------------------------------------------------------------------- */
110 /* --------------------------------------------------------------------- */
113 static volatile int totblock= 0;
114 static volatile uintptr_t mem_in_use= 0, mmap_in_use= 0;
116 static volatile struct localListBase _membase;
117 static volatile struct localListBase *membase = &_membase;
118 static void (*error_callback)(char *) = NULL;
119 static void (*thread_lock_callback)(void) = NULL;
120 static void (*thread_unlock_callback)(void) = NULL;
122 static int malloc_debug_memset= 0;
137 /* --------------------------------------------------------------------- */
139 /* --------------------------------------------------------------------- */
141 static void print_error(const char *str, ...)
147 vsprintf(buf, str, ap);
150 if (error_callback) error_callback(buf);
153 static void mem_lock_thread()
155 if (thread_lock_callback)
156 thread_lock_callback();
159 static void mem_unlock_thread()
161 if (thread_unlock_callback)
162 thread_unlock_callback();
165 int MEM_check_memory_integrity()
167 const char* err_val = NULL;
169 /* check_memlist starts from the front, and runs until it finds
170 * the requested chunk. For this test, that's the last one. */
171 listend = membase->last;
173 err_val = check_memlist(listend);
175 if (err_val == 0) return 0;
180 void MEM_set_error_callback(void (*func)(char *))
182 error_callback = func;
185 void MEM_set_lock_callback(void (*lock)(void), void (*unlock)(void))
187 thread_lock_callback = lock;
188 thread_unlock_callback = unlock;
191 void MEM_set_memory_debug(void)
193 malloc_debug_memset= 1;
196 int MEM_allocN_len(void *vmemh)
199 MemHead *memh= vmemh;
207 void *MEM_dupallocN(void *vmemh)
212 MemHead *memh= vmemh;
216 newp= MEM_mapallocN(memh->len, "dupli_mapalloc");
218 newp= MEM_mallocN(memh->len, "dupli_alloc");
220 if (newp == NULL) return NULL;
222 memcpy(newp, vmemh, memh->len);
228 static void make_memhead_header(MemHead *memh, unsigned int len, const char *str)
232 memh->tag1 = MEMTAG1;
237 memh->tag2 = MEMTAG2;
239 memt = (MemTail *)(((char *) memh) + sizeof(MemHead) + len);
240 memt->tag3 = MEMTAG3;
242 addtail(membase,&memh->next);
243 if (memh->next) memh->nextname = MEMNEXT(memh->next)->name;
249 void *MEM_mallocN(unsigned int len, const char *str)
255 len = (len + 3 ) & ~3; /* allocate in units of 4 */
257 memh= (MemHead *)malloc(len+sizeof(MemHead)+sizeof(MemTail));
260 make_memhead_header(memh, len, str);
262 if(malloc_debug_memset && len)
263 memset(memh+1, 255, len);
267 print_error("Malloc returns nill: len=%d in %s, total %u\n",len, str, mem_in_use);
271 void *MEM_callocN(unsigned int len, const char *str)
277 len = (len + 3 ) & ~3; /* allocate in units of 4 */
279 memh= (MemHead *)calloc(len+sizeof(MemHead)+sizeof(MemTail),1);
282 make_memhead_header(memh, len, str);
287 print_error("Calloc returns nill: len=%d in %s, total %u\n",len, str, mem_in_use);
291 /* note; mmap returns zero'd memory */
292 void *MEM_mapallocN(unsigned int len, const char *str)
298 len = (len + 3 ) & ~3; /* allocate in units of 4 */
305 fd = open("/dev/zero", O_RDWR);
307 memh= mmap(0, len+sizeof(MemHead)+sizeof(MemTail),
308 PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
312 memh= mmap(0, len+sizeof(MemHead)+sizeof(MemTail),
313 PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0);
316 if(memh!=(MemHead *)-1) {
317 make_memhead_header(memh, len, str);
325 print_error("Mapalloc returns nill, fallback to regular malloc: len=%d in %s, total %u\n",len, str, mmap_in_use);
326 return MEM_callocN(len, str);
330 /* Memory statistics print */
331 typedef struct MemPrintBlock {
337 static int compare_name(const void *p1, const void *p2)
339 const MemPrintBlock *pb1= (const MemPrintBlock*)p1;
340 const MemPrintBlock *pb2= (const MemPrintBlock*)p2;
342 return strcmp(pb1->name, pb2->name);
345 static int compare_len(const void *p1, const void *p2)
347 const MemPrintBlock *pb1= (const MemPrintBlock*)p1;
348 const MemPrintBlock *pb2= (const MemPrintBlock*)p2;
350 if(pb1->len < pb2->len)
352 else if(pb1->len == pb2->len)
358 void MEM_printmemlist_stats()
361 MemPrintBlock *pb, *printblock;
366 /* put memory blocks into array */
367 printblock= malloc(sizeof(MemPrintBlock)*totblock);
372 membl = membase->first;
373 if (membl) membl = MEMNEXT(membl);
376 pb->name= membl->name;
384 membl= MEMNEXT(membl->next);
388 /* sort by name and add together blocks with the same name */
389 qsort(printblock, totpb, sizeof(MemPrintBlock), compare_name);
390 for(a=0, b=0; a<totpb; a++) {
394 else if(strcmp(printblock[a].name, printblock[b].name) == 0) {
395 printblock[b].len += printblock[a].len;
396 printblock[b].items++;
400 memcpy(&printblock[b], &printblock[a], sizeof(MemPrintBlock));
405 /* sort by length and print */
406 qsort(printblock, totpb, sizeof(MemPrintBlock), compare_len);
407 printf("\ntotal memory len: %.3f MB\n", (double)mem_in_use/(double)(1024*1024));
408 for(a=0, pb=printblock; a<totpb; a++, pb++)
409 printf("%s items: %d, len: %.3f MB\n", pb->name, pb->items, (double)pb->len/(double)(1024*1024));
416 /* Prints in python syntax for easy */
417 static void MEM_printmemlist_internal( int pydict )
423 membl = membase->first;
424 if (membl) membl = MEMNEXT(membl);
427 print_error("# membase_debug.py\n");
428 print_error("membase = [\\\n");
432 fprintf(stderr, "{'len':%i, 'name':'''%s''', 'pointer':'%p'},\\\n", membl->len, membl->name, membl+1);
434 print_error("%s len: %d %p\n",membl->name,membl->len, membl+1);
437 membl= MEMNEXT(membl->next);
441 fprintf(stderr, "]\n\n");
445 "for mb_item in membase:\n"
446 "\tmb_item_user_size = mb_userinfo.setdefault(mb_item['name'], [0,0])\n"
447 "\tmb_item_user_size[0] += 1 # Add a user\n"
448 "\tmb_item_user_size[1] += mb_item['len'] # Increment the size\n"
449 "\ttotmem += mb_item['len']\n"
450 "print '(membase) items:', len(membase), '| unique-names:', len(mb_userinfo), '| total-mem:', totmem\n"
451 "mb_userinfo_sort = mb_userinfo.items()\n"
452 "for sort_name, sort_func in (('size', lambda a: -a[1][1]), ('users', lambda a: -a[1][0]), ('name', lambda a: a[0])):\n"
453 "\tprint '\\nSorting by:', sort_name\n"
454 "\tmb_userinfo_sort.sort(key = sort_func)\n"
455 "\tfor item in mb_userinfo_sort:\n"
456 "\t\tprint 'name:%%s, users:%%i, len:%%i' %% (item[0], item[1][0], item[1][1])\n"
463 void MEM_printmemlist( void ) {
464 MEM_printmemlist_internal(0);
466 void MEM_printmemlist_pydict( void ) {
467 MEM_printmemlist_internal(1);
470 short MEM_freeN(void *vmemh) /* anders compileertie niet meer */
474 MemHead *memh= vmemh;
478 MemorY_ErroR("free","attempt to free NULL pointer");
479 /* print_error(err_stream, "%d\n", (memh+4000)->tag1); */
483 if(sizeof(intptr_t)==8) {
484 if (((intptr_t) memh) & 0x7) {
485 MemorY_ErroR("free","attempt to free illegal pointer");
490 if (((intptr_t) memh) & 0x3) {
491 MemorY_ErroR("free","attempt to free illegal pointer");
497 if(memh->tag1 == MEMFREE && memh->tag2 == MEMFREE) {
498 MemorY_ErroR(memh->name,"double free");
504 if ((memh->tag1 == MEMTAG1) && (memh->tag2 == MEMTAG2) && ((memh->len & 0x3) == 0)) {
505 memt = (MemTail *)(((char *) memh) + sizeof(MemHead) + memh->len);
506 if (memt->tag3 == MEMTAG3){
508 memh->tag1 = MEMFREE;
509 memh->tag2 = MEMFREE;
510 memt->tag3 = MEMFREE;
519 MemorY_ErroR(memh->name,"end corrupt");
520 name = check_memlist(memh);
522 if (name != memh->name) MemorY_ErroR(name,"is also corrupt");
526 name = check_memlist(memh);
528 MemorY_ErroR("free","pointer not in memlist");
530 MemorY_ErroR(name,"error in header");
534 /* here a DUMP should happen */
541 /* --------------------------------------------------------------------- */
542 /* local functions */
543 /* --------------------------------------------------------------------- */
545 static void addtail(volatile localListBase *listbase, void *vlink)
547 struct localLink *link= vlink;
549 if (link == 0) return;
550 if (listbase == 0) return;
553 link->prev = listbase->last;
555 if (listbase->last) ((struct localLink *)listbase->last)->next = link;
556 if (listbase->first == 0) listbase->first = link;
557 listbase->last = link;
560 static void remlink(volatile localListBase *listbase, void *vlink)
562 struct localLink *link= vlink;
564 if (link == 0) return;
565 if (listbase == 0) return;
567 if (link->next) link->next->prev = link->prev;
568 if (link->prev) link->prev->next = link->next;
570 if (listbase->last == link) listbase->last = link->prev;
571 if (listbase->first == link) listbase->first = link->next;
574 static void rem_memblock(MemHead *memh)
576 remlink(membase,&memh->next);
579 MEMNEXT(memh->prev)->nextname = MEMNEXT(memh->next)->name;
581 MEMNEXT(memh->prev)->nextname = NULL;
585 mem_in_use -= memh->len;
588 mmap_in_use -= memh->len;
589 if (munmap(memh, memh->len + sizeof(MemHead) + sizeof(MemTail)))
590 printf("Couldn't unmap memory %s\n", memh->name);
593 if(malloc_debug_memset && memh->len)
594 memset(memh+1, 255, memh->len);
599 static void MemorY_ErroR(const char *block, const char *error)
601 print_error("Memoryblock %s: %s\n",block, error);
604 static const char *check_memlist(MemHead *memh)
606 MemHead *forw,*back,*forwok,*backok;
609 forw = membase->first;
610 if (forw) forw = MEMNEXT(forw);
613 if (forw->tag1 != MEMTAG1 || forw->tag2 != MEMTAG2) break;
615 if (forw->next) forw = MEMNEXT(forw->next);
619 back = (MemHead *) membase->last;
620 if (back) back = MEMNEXT(back);
623 if (back->tag1 != MEMTAG1 || back->tag2 != MEMTAG2) break;
625 if (back->prev) back = MEMNEXT(back->prev);
629 if (forw != back) return ("MORE THAN 1 MEMORYBLOCK CORRUPT");
631 if (forw == 0 && back == 0){
632 /* geen foute headers gevonden dan maar op zoek naar memblock*/
634 forw = membase->first;
635 if (forw) forw = MEMNEXT(forw);
638 if (forw == memh) break;
639 if (forw->tag1 != MEMTAG1 || forw->tag2 != MEMTAG2) break;
641 if (forw->next) forw = MEMNEXT(forw->next);
644 if (forw == 0) return (0);
646 back = (MemHead *) membase->last;
647 if (back) back = MEMNEXT(back);
650 if (back == memh) break;
651 if (back->tag1 != MEMTAG1 || back->tag2 != MEMTAG2) break;
653 if (back->prev) back = MEMNEXT(back->prev);
658 if (forwok) name = forwok->nextname;
659 else name = "No name found";
662 /* voor alle zekerheid wordt dit block maar uit de lijst gehaald */
665 forwok->next = (MemHead *)&backok->next;
666 backok->prev = (MemHead *)&forwok->next;
667 forwok->nextname = backok->name;
670 membase->last = (struct localLink *) &forwok->next;
671 /* membase->last = (struct Link *) &forwok->next; */
676 membase->first = &backok->next;
678 membase->first = membase->last = 0;
682 MemorY_ErroR(name,"Additional error in header");
683 return("Additional error in header");
689 uintptr_t MEM_get_memory_in_use(void)
691 uintptr_t _mem_in_use;
694 _mem_in_use= mem_in_use;
700 uintptr_t MEM_get_mapped_memory_in_use(void)
702 uintptr_t _mmap_in_use;
705 _mmap_in_use= mmap_in_use;
711 int MEM_get_memory_blocks_in_use(void)