memtrack.c 7.67 KB
Newer Older
1
/*  dvdisaster: Additional error correction for optical media.
2
 *  Copyright (C) 2004-2015 Carsten Gnoerlich.
3
 *
4 5 6 7 8 9
 *  Email: carsten@dvdisaster.org  -or-  cgnoerlich@fsfe.org
 *  Project homepage: http://www.dvdisaster.org
 *
 *  This file is part of dvdisaster.
 *
 *  dvdisaster is free software: you can redistribute it and/or modify
10
 *  it under the terms of the GNU General Public License as published by
11
 *  the Free Software Foundation, either version 3 of the License, or
12 13
 *  (at your option) any later version.
 *
14
 *  dvdisaster is distributed in the hope that it will be useful,
15 16 17 18 19
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
20
 *  along with dvdisaster. If not, see <http://www.gnu.org/licenses/>.
21 22 23 24
 */

#define _GNU_SOURCE

25
#if !defined(SYS_FREEBSD)   /* FreeBSD declares malloc() in stdlib.h */
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
 #include <malloc.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <glib.h>
#include <glib/gprintf.h>

/*
 * We're not pulling in dvdisaster.h on purpose...
 */

void Stop(char*, ...);

/***
 *** Special routines for keeping track of memory allocation.
 ***
 * memtrack.c currently uses malloc() and friends.
 * This is probably a bad idea for those operating systems where g_malloc()
 * and malloc() are different and not compatible. 
 * We must keep an eye on that.
 */

/***
 *** Keeping track of allocated pointers. 
 ***/

/*
 * A structure containing info about each pointer which was
 * produced through our memory allocation routines.
 */

typedef struct _memchunk
{  void *ptr;	/* allocated memory chunk */
   int size;	/* size of chunk */
   char *file;	/* source file this was allocated in */
   int  line;	/* line number of source file */
} memchunk;

/*
 * Since we're compiled in optionally,
 * we do not use the common Closure struct.
 */

static struct _memchunk **ptrhash[64];	/* 64 buckets of memory chunks */
static int phCnt[64];
static int phMax[64];
static int currentAllocation;		/* current memory allocation */
static int peakAllocation;		/* maximum allocation */
76
static GMutex phMutex;
77 78 79 80 81 82 83 84 85

/*
 * Remember an allocated pointer. 
 */

void remember(void *ptr, int size, char *file, int line)
{  memchunk *mc;
   int hash_idx;

86
   g_mutex_lock(&phMutex);
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

   hash_idx = (((long)ptr)>>3)&63;
   if(phCnt[hash_idx] >= phMax[hash_idx])
   {  if(!phMax[hash_idx]) phMax[hash_idx] = 16;
      else                 phMax[hash_idx] *= 2;
      if(!(ptrhash[hash_idx] = realloc(ptrhash[hash_idx], sizeof(memchunk*)*phMax[hash_idx])))
	 Stop("can't realloc memchunk hashtable");
   }

   if(!(mc=malloc(sizeof(memchunk))))
      Stop("can't alloc memchunk");

   ptrhash[hash_idx][phCnt[hash_idx]++] = mc;

   mc->ptr   = ptr;
   mc->size  = size;
   mc->file  = file;
   mc->line  = line;

   currentAllocation += size;
   if(currentAllocation > peakAllocation)
      peakAllocation = currentAllocation;

110
   g_mutex_unlock(&phMutex);
111 112 113 114 115 116 117
} 

/*
 * Remove a remembered pointer from the hash bucket.
 */

int forget(void *ptr)
118
{  memchunk **ptrlist;
119 120 121
   int hash_idx;
   int i;

122
   g_mutex_lock(&phMutex);
123 124 125 126 127 128 129 130 131 132 133 134

   hash_idx = (((long)ptr)>>3)&63;
   ptrlist = ptrhash[hash_idx];

   for(i=0; i<phCnt[hash_idx]; i++)
      if(ptrlist[i]->ptr==ptr)
      {  currentAllocation -= ptrlist[i]->size;
	 free(ptrlist[i]);
         phCnt[hash_idx]--;
	 if(phCnt[hash_idx] > 0)
	    ptrlist[i] = ptrlist[phCnt[hash_idx]];

135
	 g_mutex_unlock(&phMutex);
136 137 138
         return 0;
      }

139
   g_mutex_unlock(&phMutex);
140 141 142 143 144 145 146 147 148 149
   return 1;
}

/*
 * Print the contents of the ptrlist.
 */

static void print_ptr(memchunk *mc, int size)
{  char strbuf[16];
   char *ptr = (char*)mc->ptr; 
150 151 152
   int j;

   /* print the pointer */
153 154 155 156 157 158

   for(j=0; j<15; j++)
   {  if(ptr[j]<32) break;
      strbuf[j] = ptr[j];
   } 

159 160 161 162 163 164 165 166 167 168
#ifdef HAVE_64BIT
   if(j) 
   {  strbuf[j]=0;
      g_printf("Address 0x%llx (\"%s\"), %d bytes, from %s, line %d\n",
	       (unsigned long long)mc->ptr,strbuf,mc->size,mc->file,mc->line);
   }
   else 
     g_printf("Address 0x%llx (binary data), %d bytes, from %s, line %d\n",
	      (unsigned long long)mc->ptr,mc->size,mc->file,mc->line);
#else /* hopefully 32BIT */
169 170 171 172 173 174 175 176
   if(j) 
   {  strbuf[j]=0;
      g_printf("Address 0x%lx (\"%s\"), %d bytes, from %s, line %d\n",
	       (unsigned long)mc->ptr,strbuf,mc->size,mc->file,mc->line);
   }
   else 
     g_printf("Address 0x%lx (binary data), %d bytes, from %s, line %d\n",
	      (unsigned long)mc->ptr,mc->size,mc->file,mc->line);
177
#endif
178 179 180 181 182
}

static void print_ptrs(char *msg)
{  int bucket,i,n=0;

183
   g_printf("%s", msg);
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

   for(bucket=0; bucket<64; bucket++)
      for(i=0; i<phCnt[bucket]; i++)
      {  
	 print_ptr(ptrhash[bucket][i], 15);
	 n++;
      }

   g_printf("%d memory chunks total.\n",n);

}

/***
 *** Replacements for the libc memory allocators.
 ***/

/* 
 * Protected malloc().
 */

void *malloc_ext(int size, char* file, int line)
{  void *ptr;
#if 0
   printf("allocating %d bytes from file %s, line %d\n", size, file, line); 
#endif
   if(!(ptr = calloc(1,size)))
      Stop("out of memory while allocating %d bytes",size);

   remember(ptr,size,file,line);

   return ptr;
}

/* 
 * Protected try_malloc().
 */

void *try_malloc_ext(int size, char* file, int line)
{  void *ptr;

   if((ptr = calloc(1,size)))
     remember(ptr,size,file,line);

   return ptr;
}

/* 
 * Protected realloc(). 
 */

void *realloc_ext(void *ptr, int size, char *file, int line)
{  void *ret;

   if(ptr && forget(ptr))
   {  g_printf("trying to realloc undefined pointer 0x%lx\n"
	       "file: %s, line: %d",(long)ptr,file,line);
      exit(EXIT_FAILURE);
   }

   if(!(ret=realloc(ptr,size)))
   {  g_printf("out of memory for ptr 0x%lx, %d bytes\n",(long)ptr,size);
      exit(EXIT_FAILURE);
   }

   remember(ret,size,file,line);

   return ret;
}

/* 
 * Free and forget a pointer
 */

void free_ext(void *ptr, char *file, int line)
{ 
   if(forget(ptr))
   {  g_printf("trying to free undefined pointer 0x%lx\n"
	       "file: %s, line: %d",(long)ptr,file,line);
      exit(EXIT_FAILURE);
   }

   free(ptr);
}

/*
 * String duplication.
 */

char *strdup_ext(const char *string, char *file, int line)
{  int length = strlen(string)+1;
   char *copy;

   if(!(copy = calloc(1,length)))
      Stop("out of memory while allocating %d bytes",length);

   strcpy(copy,string);
   remember(copy,length,file,line);
   return copy;
}

/* 
 * The allocating printf()s 
 */

char* strdup_printf_ext(char *format, char *file, int line, ...)
{  va_list argp;
   char *ret;

   va_start(argp,line);
   ret = g_strdup_vprintf(format, argp);
   remember(ret,strlen(ret),file,line);
   va_end(argp);

   return ret;
}

char* strdup_vprintf_ext(char *format, va_list ap, char *file, int line)
{  char *ret; 

   ret = g_strdup_vprintf(format, ap);
   remember(ret,strlen(ret),file,line);

   return ret;
}

/*
 * The utf8 converter
 */

gchar* g_locale_to_utf8_ext(const gchar *str, gssize len,
			    gsize *bytes_read, gsize *bytes_written_out, GError **error,
			    char *file, int line)
{  char *ret;
   gsize bytes_written; 

   ret = g_locale_to_utf8(str, len, bytes_read, &bytes_written, error);
   remember(ret, bytes_written, file, line);

   if(bytes_written_out)
     *bytes_written_out = bytes_written;

   return ret;
}

/***
 *** Checking for memory leaks.
 ***/

void check_memleaks(void)
{  int i,memleak = 0;

   /*** See if some memory chunks have been left over */
 
   for(i=0; i<64; i++)
      if(phCnt[i])
	 memleak = 1;

   if(memleak)
   {  char msg[80];

      sprintf(msg,"\ndvdisaster:\nMemory leak warning,"
	      " non-freed memory chunks detected.\n\n");
      print_ptrs(msg);
   }
348
   else g_printf("dvdisaster: No memory leaks found.\n");
349 350
}