4afa620a0e6c054c7ab591c59679040f0f49b0a0
[platform/upstream/curl.git] / lib / memdebug.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "curl_setup.h"
24
25 #ifdef CURLDEBUG
26
27 #include <curl/curl.h>
28
29 #define _MPRINTF_REPLACE
30 #include <curl/mprintf.h>
31 #include "urldata.h"
32
33 #define MEMDEBUG_NODEFINES /* don't redefine the standard functions */
34 #include "curl_memory.h"
35 #include "memdebug.h"
36
37 #ifndef HAVE_ASSERT_H
38 #  define assert(x) Curl_nop_stmt
39 #endif
40
41 /*
42  * Until 2011-08-17 libcurl's Memory Tracking feature also performed
43  * automatic malloc and free filling operations using 0xA5 and 0x13
44  * values. Our own preinitialization of dynamically allocated memory
45  * might be useful when not using third party memory debuggers, but
46  * on the other hand this would fool memory debuggers into thinking
47  * that all dynamically allocated memory is properly initialized.
48  *
49  * As a default setting, libcurl's Memory Tracking feature no longer
50  * performs preinitialization of dynamically allocated memory on its
51  * own. If you know what you are doing, and really want to retain old
52  * behavior, you can achieve this compiling with preprocessor symbols
53  * CURL_MT_MALLOC_FILL and CURL_MT_FREE_FILL defined with appropriate
54  * values.
55  */
56
57 #ifdef CURL_MT_MALLOC_FILL
58 # if (CURL_MT_MALLOC_FILL < 0) || (CURL_MT_MALLOC_FILL > 0xff)
59 #   error "invalid CURL_MT_MALLOC_FILL or out of range"
60 # endif
61 #endif
62
63 #ifdef CURL_MT_FREE_FILL
64 # if (CURL_MT_FREE_FILL < 0) || (CURL_MT_FREE_FILL > 0xff)
65 #   error "invalid CURL_MT_FREE_FILL or out of range"
66 # endif
67 #endif
68
69 #if defined(CURL_MT_MALLOC_FILL) && defined(CURL_MT_FREE_FILL)
70 # if (CURL_MT_MALLOC_FILL == CURL_MT_FREE_FILL)
71 #   error "CURL_MT_MALLOC_FILL same as CURL_MT_FREE_FILL"
72 # endif
73 #endif
74
75 #ifdef CURL_MT_MALLOC_FILL
76 #  define mt_malloc_fill(buf,len) memset((buf), CURL_MT_MALLOC_FILL, (len))
77 #else
78 #  define mt_malloc_fill(buf,len) Curl_nop_stmt
79 #endif
80
81 #ifdef CURL_MT_FREE_FILL
82 #  define mt_free_fill(buf,len) memset((buf), CURL_MT_FREE_FILL, (len))
83 #else
84 #  define mt_free_fill(buf,len) Curl_nop_stmt
85 #endif
86
87 struct memdebug {
88   size_t size;
89   union {
90     curl_off_t o;
91     double d;
92     void * p;
93   } mem[1];
94   /* I'm hoping this is the thing with the strictest alignment
95    * requirements.  That also means we waste some space :-( */
96 };
97
98 /*
99  * Note that these debug functions are very simple and they are meant to
100  * remain so. For advanced analysis, record a log file and write perl scripts
101  * to analyze them!
102  *
103  * Don't use these with multithreaded test programs!
104  */
105
106 #define logfile curl_debuglogfile
107 FILE *curl_debuglogfile = NULL;
108 static bool memlimit = FALSE; /* enable memory limit */
109 static long memsize = 0;  /* set number of mallocs allowed */
110
111 /* this sets the log file name */
112 void curl_memdebug(const char *logname)
113 {
114   if(!logfile) {
115     if(logname && *logname)
116       logfile = fopen(logname, "w");
117     else
118       logfile = stderr;
119 #ifdef MEMDEBUG_LOG_SYNC
120     /* Flush the log file after every line so the log isn't lost in a crash */
121     setvbuf(logfile, (char *)NULL, _IOLBF, 0);
122 #endif
123   }
124 }
125
126 /* This function sets the number of malloc() calls that should return
127    successfully! */
128 void curl_memlimit(long limit)
129 {
130   if(!memlimit) {
131     memlimit = TRUE;
132     memsize = limit;
133   }
134 }
135
136 /* returns TRUE if this isn't allowed! */
137 static bool countcheck(const char *func, int line, const char *source)
138 {
139   /* if source is NULL, then the call is made internally and this check
140      should not be made */
141   if(memlimit && source) {
142     if(!memsize) {
143       if(source) {
144         /* log to file */
145         curl_memlog("LIMIT %s:%d %s reached memlimit\n",
146                     source, line, func);
147         /* log to stderr also */
148         fprintf(stderr, "LIMIT %s:%d %s reached memlimit\n",
149                 source, line, func);
150       }
151       SET_ERRNO(ENOMEM);
152       return TRUE; /* RETURN ERROR! */
153     }
154     else
155       memsize--; /* countdown */
156
157     /* log the countdown */
158     if(source)
159       curl_memlog("LIMIT %s:%d %ld ALLOCS left\n",
160                   source, line, memsize);
161
162   }
163
164   return FALSE; /* allow this */
165 }
166
167 void *curl_domalloc(size_t wantedsize, int line, const char *source)
168 {
169   struct memdebug *mem;
170   size_t size;
171
172   assert(wantedsize != 0);
173
174   if(countcheck("malloc", line, source))
175     return NULL;
176
177   /* alloc at least 64 bytes */
178   size = sizeof(struct memdebug)+wantedsize;
179
180   mem = (Curl_cmalloc)(size);
181   if(mem) {
182     /* fill memory with junk */
183     mt_malloc_fill(mem->mem, wantedsize);
184     mem->size = wantedsize;
185   }
186
187   if(source)
188     curl_memlog("MEM %s:%d malloc(%zu) = %p\n",
189                 source, line, wantedsize,
190                 mem ? (void *)mem->mem : (void *)0);
191
192   return (mem ? mem->mem : NULL);
193 }
194
195 void *curl_docalloc(size_t wanted_elements, size_t wanted_size,
196                     int line, const char *source)
197 {
198   struct memdebug *mem;
199   size_t size, user_size;
200
201   assert(wanted_elements != 0);
202   assert(wanted_size != 0);
203
204   if(countcheck("calloc", line, source))
205     return NULL;
206
207   /* alloc at least 64 bytes */
208   user_size = wanted_size * wanted_elements;
209   size = sizeof(struct memdebug) + user_size;
210
211   mem = (Curl_ccalloc)(1, size);
212   if(mem)
213     mem->size = user_size;
214
215   if(source)
216     curl_memlog("MEM %s:%d calloc(%zu,%zu) = %p\n",
217                 source, line, wanted_elements, wanted_size,
218                 mem ? (void *)mem->mem : (void *)0);
219
220   return (mem ? mem->mem : NULL);
221 }
222
223 char *curl_dostrdup(const char *str, int line, const char *source)
224 {
225   char *mem;
226   size_t len;
227
228   assert(str != NULL);
229
230   if(countcheck("strdup", line, source))
231     return NULL;
232
233   len=strlen(str)+1;
234
235   mem=curl_domalloc(len, 0, NULL); /* NULL prevents logging */
236   if(mem)
237     memcpy(mem, str, len);
238
239   if(source)
240     curl_memlog("MEM %s:%d strdup(%p) (%zu) = %p\n",
241                 source, line, (void *)str, len, (void *)mem);
242
243   return mem;
244 }
245
246 #if defined(WIN32) && defined(UNICODE)
247 wchar_t *curl_dowcsdup(const wchar_t *str, int line, const char *source)
248 {
249   wchar_t *mem;
250   size_t wsiz, bsiz;
251
252   assert(str != NULL);
253
254   if(countcheck("wcsdup", line, source))
255     return NULL;
256
257   wsiz = wcslen(str) + 1;
258   bsiz = wsiz * sizeof(wchar_t);
259
260   mem = curl_domalloc(bsiz, 0, NULL); /* NULL prevents logging */
261   if(mem)
262     memcpy(mem, str, bsiz);
263
264   if(source)
265     curl_memlog("MEM %s:%d wcsdup(%p) (%zu) = %p\n",
266                 source, line, (void *)str, bsiz, (void *)mem);
267
268   return mem;
269 }
270 #endif
271
272 /* We provide a realloc() that accepts a NULL as pointer, which then
273    performs a malloc(). In order to work with ares. */
274 void *curl_dorealloc(void *ptr, size_t wantedsize,
275                      int line, const char *source)
276 {
277   struct memdebug *mem=NULL;
278
279   size_t size = sizeof(struct memdebug)+wantedsize;
280
281   assert(wantedsize != 0);
282
283   if(countcheck("realloc", line, source))
284     return NULL;
285
286 #ifdef __INTEL_COMPILER
287 #  pragma warning(push)
288 #  pragma warning(disable:1684)
289    /* 1684: conversion from pointer to same-sized integral type */
290 #endif
291
292   if(ptr)
293     mem = (void *)((char *)ptr - offsetof(struct memdebug, mem));
294
295 #ifdef __INTEL_COMPILER
296 #  pragma warning(pop)
297 #endif
298
299   mem = (Curl_crealloc)(mem, size);
300   if(source)
301     curl_memlog("MEM %s:%d realloc(%p, %zu) = %p\n",
302                 source, line, (void *)ptr, wantedsize,
303                 mem ? (void *)mem->mem : (void *)0);
304
305   if(mem) {
306     mem->size = wantedsize;
307     return mem->mem;
308   }
309
310   return NULL;
311 }
312
313 void curl_dofree(void *ptr, int line, const char *source)
314 {
315   struct memdebug *mem;
316
317   if(ptr) {
318
319 #ifdef __INTEL_COMPILER
320 #  pragma warning(push)
321 #  pragma warning(disable:1684)
322    /* 1684: conversion from pointer to same-sized integral type */
323 #endif
324
325     mem = (void *)((char *)ptr - offsetof(struct memdebug, mem));
326
327 #ifdef __INTEL_COMPILER
328 #  pragma warning(pop)
329 #endif
330
331     /* destroy */
332     mt_free_fill(mem->mem, mem->size);
333
334     /* free for real */
335     (Curl_cfree)(mem);
336   }
337
338   if(source)
339     curl_memlog("MEM %s:%d free(%p)\n", source, line, (void *)ptr);
340 }
341
342 curl_socket_t curl_socket(int domain, int type, int protocol,
343                           int line, const char *source)
344 {
345   const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
346                     "FD %s:%d socket() = %d\n" :
347                     (sizeof(curl_socket_t) == sizeof(long)) ?
348                     "FD %s:%d socket() = %ld\n" :
349                     "FD %s:%d socket() = %zd\n" ;
350
351   curl_socket_t sockfd = socket(domain, type, protocol);
352
353   if(source && (sockfd != CURL_SOCKET_BAD))
354     curl_memlog(fmt, source, line, sockfd);
355
356   return sockfd;
357 }
358
359 #ifdef HAVE_SOCKETPAIR
360 int curl_socketpair(int domain, int type, int protocol,
361                     curl_socket_t socket_vector[2],
362                     int line, const char *source)
363 {
364   const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
365                     "FD %s:%d socketpair() = %d %d\n" :
366                     (sizeof(curl_socket_t) == sizeof(long)) ?
367                     "FD %s:%d socketpair() = %ld %ld\n" :
368                     "FD %s:%d socketpair() = %zd %zd\n" ;
369
370   int res = socketpair(domain, type, protocol, socket_vector);
371
372   if(source && (0 == res))
373     curl_memlog(fmt, source, line, socket_vector[0], socket_vector[1]);
374
375   return res;
376 }
377 #endif
378
379 curl_socket_t curl_accept(curl_socket_t s, void *saddr, void *saddrlen,
380                           int line, const char *source)
381 {
382   const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
383                     "FD %s:%d accept() = %d\n" :
384                     (sizeof(curl_socket_t) == sizeof(long)) ?
385                     "FD %s:%d accept() = %ld\n" :
386                     "FD %s:%d accept() = %zd\n" ;
387
388   struct sockaddr *addr = (struct sockaddr *)saddr;
389   curl_socklen_t *addrlen = (curl_socklen_t *)saddrlen;
390
391   curl_socket_t sockfd = accept(s, addr, addrlen);
392
393   if(source && (sockfd != CURL_SOCKET_BAD))
394     curl_memlog(fmt, source, line, sockfd);
395
396   return sockfd;
397 }
398
399 /* separate function to allow libcurl to mark a "faked" close */
400 void curl_mark_sclose(curl_socket_t sockfd, int line, const char *source)
401 {
402   const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
403                     "FD %s:%d sclose(%d)\n" :
404                     (sizeof(curl_socket_t) == sizeof(long)) ?
405                     "FD %s:%d sclose(%ld)\n" :
406                     "FD %s:%d sclose(%zd)\n" ;
407
408   if(source)
409     curl_memlog(fmt, source, line, sockfd);
410 }
411
412 /* this is our own defined way to close sockets on *ALL* platforms */
413 int curl_sclose(curl_socket_t sockfd, int line, const char *source)
414 {
415   int res=sclose(sockfd);
416   curl_mark_sclose(sockfd, line, source);
417   return res;
418 }
419
420 FILE *curl_fopen(const char *file, const char *mode,
421                  int line, const char *source)
422 {
423   FILE *res=fopen(file, mode);
424
425   if(source)
426     curl_memlog("FILE %s:%d fopen(\"%s\",\"%s\") = %p\n",
427                 source, line, file, mode, (void *)res);
428
429   return res;
430 }
431
432 #ifdef HAVE_FDOPEN
433 FILE *curl_fdopen(int filedes, const char *mode,
434                   int line, const char *source)
435 {
436   FILE *res=fdopen(filedes, mode);
437
438   if(source)
439     curl_memlog("FILE %s:%d fdopen(\"%d\",\"%s\") = %p\n",
440                 source, line, filedes, mode, (void *)res);
441
442   return res;
443 }
444 #endif
445
446 int curl_fclose(FILE *file, int line, const char *source)
447 {
448   int res;
449
450   assert(file != NULL);
451
452   res=fclose(file);
453
454   if(source)
455     curl_memlog("FILE %s:%d fclose(%p)\n",
456                 source, line, (void *)file);
457
458   return res;
459 }
460
461 #define LOGLINE_BUFSIZE  1024
462
463 /* this does the writting to the memory tracking log file */
464 void curl_memlog(const char *format, ...)
465 {
466   char *buf;
467   int nchars;
468   va_list ap;
469
470   if(!logfile)
471     return;
472
473   buf = (Curl_cmalloc)(LOGLINE_BUFSIZE);
474   if(!buf)
475     return;
476
477   va_start(ap, format);
478   nchars = vsnprintf(buf, LOGLINE_BUFSIZE, format, ap);
479   va_end(ap);
480
481   if(nchars > LOGLINE_BUFSIZE - 1)
482     nchars = LOGLINE_BUFSIZE - 1;
483
484   if(nchars > 0)
485     fwrite(buf, 1, nchars, logfile);
486
487   (Curl_cfree)(buf);
488 }
489
490 #endif /* CURLDEBUG */