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