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