Commit 02c78ecf authored by Daniel Stenberg's avatar Daniel Stenberg
Browse files

allow out-of-memory testing by setting a limit. That number of memory

allocation calls will succeed, the following will return NULL!
parent caca0343
Loading
Loading
Loading
Loading
+45 −1
Original line number Diff line number Diff line
@@ -62,7 +62,10 @@ struct memdebug {
 * Don't use these with multithreaded test programs!
 */

FILE *logfile;
#define logfile curl_debuglogfile
FILE *curl_debuglogfile;
static bool memlimit; /* enable memory limit */
static long memsize;  /* set number of mallocs allowed */

/* this sets the log file name */
void curl_memdebug(const char *logname)
@@ -73,12 +76,47 @@ void curl_memdebug(const char *logname)
    logfile = stderr;
}

/* This function sets the number of malloc() calls that should return
   successfully! */
void curl_memlimit(long limit)
{
  memlimit = TRUE;
  memsize = limit;
}

/* returns TRUE if this isn't allowed! */
static bool countcheck(const char *func, int line, const char *source)
{
  /* if source is NULL, then the call is made internally and this check
     should not be made */
  if(memlimit && source) {
    if(!memsize) {
      if(logfile && source)
        fprintf(logfile, "LIMIT %s:%d %s reached memlimit\n",
                source, line, func);
      return TRUE; /* RETURN ERROR! */
    }
    else
      memsize--; /* countdown */
    
    /* log the countdown */
    if(logfile && source)
      fprintf(logfile, "LIMIT %s:%d %ld ALLOCS left\n",
              source, line, memsize);
    
  }

  return FALSE; /* allow this */
}

void *curl_domalloc(size_t wantedsize, int line, const char *source)
{
  struct memdebug *mem;
  size_t size;

  if(countcheck("malloc", line, source))
    return NULL;

  /* alloc at least 64 bytes */
  size = sizeof(struct memdebug)+wantedsize;

@@ -106,6 +144,9 @@ char *curl_dostrdup(const char *str, int line, const char *source)
    exit(2);
  }

  if(countcheck("strdup", line, source))
    return NULL;

  len=strlen(str)+1;

  mem=curl_domalloc(len, 0, NULL); /* NULL prevents logging */
@@ -125,6 +166,9 @@ void *curl_dorealloc(void *ptr, size_t wantedsize,

  size_t size = sizeof(struct memdebug)+wantedsize;

  if(countcheck("realloc", line, source))
    return NULL;

  mem = (struct memdebug *)((char *)ptr - offsetof(struct memdebug, mem));

  mem=(struct memdebug *)(realloc)(mem, size);
+3 −0
Original line number Diff line number Diff line
@@ -39,6 +39,8 @@
#include <memory.h>
#endif

#define logfile curl_debuglogfile

extern FILE *logfile;

/* memory functions */
@@ -47,6 +49,7 @@ void *curl_dorealloc(void *ptr, size_t size, int line, const char *source);
void curl_dofree(void *ptr, int line, const char *source);
char *curl_dostrdup(const char *str, int line, const char *source);
void curl_memdebug(const char *logname);
void curl_memlimit(long limit);

/* file descriptor manipulators */
int curl_socket(int domain, int type, int protocol, int, const char *);