Coverage Report

Created: 2026-12-01 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/memdebug.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) 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.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
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
26
#ifdef CURL_MEMDEBUG
27
28
#include <stddef.h>  /* for offsetof() */
29
30
#include "urldata.h"
31
#include "curl_threads.h"
32
#include "curlx/win32-fopen.h"  /* for CURLX_FOPEN_*() */
33
34
#ifdef USE_BACKTRACE
35
#include <backtrace.h>
36
#endif
37
38
struct memdebug {
39
  size_t size;
40
  size_t padding; /* keep mem aligned like malloc(), up to 16 */
41
  union {
42
    curl_off_t o;
43
    double d;
44
    void *p;
45
  } mem[1];
46
  /* I am hoping this is the thing with the strictest alignment
47
   * requirements. That also means we waste some space :-( */
48
};
49
50
/*
51
 * Note that these debug functions are simple and they are meant to remain so.
52
 * For advanced analysis, record a log file and write perl scripts to analyze
53
 * them!
54
 *
55
 * Do not use these with multi-threaded test programs!
56
 */
57
58
FILE *curl_dbg_logfile = NULL;
59
static bool registered_cleanup = FALSE; /* atexit registered cleanup */
60
static bool memlimit = FALSE; /* enable memory limit */
61
static long memsize = 0;  /* set number of mallocs allowed */
62
#ifdef USE_BACKTRACE
63
static struct backtrace_state *btstate;
64
#endif
65
66
static char membuf[10000];
67
static size_t memwidx = 0; /* write index */
68
69
#ifdef USE_MUTEX
70
static bool dbg_mutex_init = 0;
71
static curl_mutex_t dbg_mutex;
72
#endif
73
74
static bool curl_dbg_lock(void)
75
15.8M
{
76
15.8M
#ifdef USE_MUTEX
77
15.8M
  if(dbg_mutex_init) {
78
0
    Curl_mutex_acquire(&dbg_mutex);
79
0
    return TRUE;
80
0
  }
81
15.8M
#endif
82
15.8M
  return FALSE;
83
15.8M
}
84
85
static void curl_dbg_unlock(bool was_locked)
86
15.8M
{
87
15.8M
#ifdef USE_MUTEX
88
15.8M
  if(was_locked)
89
0
    Curl_mutex_release(&dbg_mutex);
90
#else
91
  (void)was_locked;
92
#endif
93
15.8M
}
94
95
static void curl_dbg_log_locked(const char *format, ...) CURL_PRINTF(1, 2);
96
97
/* LeakSantizier (LSAN) calls _exit() instead of exit() when a leak is detected
98
   on exit so the logfile must be closed explicitly or data could be lost.
99
   Though _exit() does not call atexit handlers such as this, LSAN's call to
100
   _exit() comes after the atexit handlers are called. curl/curl#6620 */
101
static void curl_dbg_cleanup(void)
102
0
{
103
0
  bool locked = curl_dbg_lock();
104
0
  if(curl_dbg_logfile &&
105
0
     curl_dbg_logfile != stderr &&
106
0
     curl_dbg_logfile != stdout) {
107
0
    if(memwidx)
108
0
      fwrite(membuf, 1, memwidx, curl_dbg_logfile);
109
    /* !checksrc! disable BANNEDFUNC 1 */
110
0
    fclose(curl_dbg_logfile);
111
0
  }
112
0
  curl_dbg_logfile = NULL;
113
0
  curl_dbg_unlock(locked);
114
0
#ifdef USE_MUTEX
115
0
  if(dbg_mutex_init) {
116
0
    Curl_mutex_destroy(&dbg_mutex);
117
0
    dbg_mutex_init = FALSE;
118
0
  }
119
0
#endif
120
0
}
121
122
#ifdef USE_BACKTRACE
123
static void error_bt_callback(void *data, const char *message,
124
                              int error_number)
125
{
126
  (void)data;
127
  if(error_number == -1)
128
    curl_dbg_log("compile with -g\n\n");
129
  else
130
    curl_dbg_log("Backtrace error %d: %s\n", error_number, message);
131
}
132
133
static int full_callback(void *data, uintptr_t pc, const char *pathname,
134
                         int line_number, const char *function)
135
{
136
  (void)data;
137
  (void)pc;
138
  if(pathname || function || line_number)
139
    curl_dbg_log("BT %s:%d -- %s\n", pathname, line_number, function);
140
  return 0;
141
}
142
143
static void dump_bt(void)
144
{
145
  backtrace_full(btstate, 0, full_callback, error_bt_callback, NULL);
146
}
147
#else
148
#define dump_bt() /* nothing to do */
149
#endif
150
151
/* this sets the log filename */
152
void curl_dbg_memdebug(const char *logname)
153
0
{
154
0
  if(!curl_dbg_logfile) {
155
0
    if(logname && *logname)
156
0
      curl_dbg_logfile = CURLX_FOPEN_LOW(logname, FOPEN_WRITETEXT);
157
#ifdef MEMDEBUG_LOG_SYNC
158
    /* Flush the log file after every line so the log is not lost in a crash */
159
    if(curl_dbg_logfile)
160
      setbuf(curl_dbg_logfile, (char *)NULL);
161
#endif
162
0
  }
163
0
#ifdef USE_MUTEX
164
0
  if(!dbg_mutex_init) {
165
0
    dbg_mutex_init = TRUE;
166
0
    Curl_mutex_init(&dbg_mutex);
167
0
  }
168
0
#endif
169
#ifdef USE_BACKTRACE
170
  btstate = backtrace_create_state(NULL, 0, error_bt_callback, NULL);
171
#endif
172
0
  if(!registered_cleanup)
173
0
    registered_cleanup = !atexit(curl_dbg_cleanup);
174
0
}
175
176
/* This function sets the number of malloc() calls that should return
177
   successfully! */
178
void curl_dbg_memlimit(long limit)
179
0
{
180
0
  if(!memlimit) {
181
0
    memlimit = TRUE;
182
0
    memsize = limit;
183
0
  }
184
0
}
185
186
/* returns TRUE if this is not allowed! */
187
static bool countcheck(const char *func, int line, const char *source)
188
74.7M
{
189
  /* if source is NULL, then the call is made internally and this check
190
     should not be made */
191
74.7M
  if(memlimit && source) {
192
0
    if(!memsize) {
193
      /* log to file */
194
0
      curl_dbg_log("LIMIT %s:%d %s reached memlimit\n", source, line, func);
195
      /* log to stderr also */
196
0
      curl_mfprintf(stderr, "LIMIT %s:%d %s reached memlimit\n",
197
0
                    source, line, func);
198
0
      dump_bt();
199
0
      fflush(curl_dbg_logfile); /* because it might crash now */
200
      /* !checksrc! disable ERRNOVAR 1 */
201
0
      errno = ENOMEM;
202
0
      return TRUE; /* RETURN ERROR! */
203
0
    }
204
0
    else
205
0
      memsize--; /* countdown */
206
0
  }
207
208
74.7M
  return FALSE; /* allow this */
209
74.7M
}
210
211
ALLOC_FUNC
212
void *curl_dbg_malloc(size_t wantedsize, int line, const char *source)
213
19.4M
{
214
19.4M
  struct memdebug *mem;
215
19.4M
  size_t size;
216
217
19.4M
  DEBUGASSERT(wantedsize != 0);
218
219
19.4M
  if(countcheck("malloc", line, source))
220
0
    return NULL;
221
222
  /* alloc at least 64 bytes */
223
19.4M
  size = sizeof(struct memdebug) + wantedsize;
224
225
19.4M
  mem = Curl_cmalloc(size);
226
19.4M
  if(mem) {
227
19.3M
    mem->size = wantedsize;
228
19.3M
  }
229
230
19.4M
  if(source)
231
14.0M
    curl_dbg_log("MEM %s:%d malloc(%zu) = %p\n",
232
14.0M
                 source, line, wantedsize,
233
14.0M
                 mem ? (void *)mem->mem : (void *)0);
234
235
19.4M
  return mem ? mem->mem : NULL;
236
19.4M
}
237
238
ALLOC_FUNC
239
void *curl_dbg_calloc(size_t wanted_elements, size_t wanted_size,
240
                      int line, const char *source)
241
33.6M
{
242
33.6M
  struct memdebug *mem;
243
33.6M
  size_t size, user_size;
244
245
33.6M
  DEBUGASSERT(wanted_elements != 0);
246
33.6M
  DEBUGASSERT(wanted_size != 0);
247
248
33.6M
  if(countcheck("calloc", line, source))
249
0
    return NULL;
250
251
  /* alloc at least 64 bytes */
252
33.6M
  user_size = wanted_size * wanted_elements;
253
33.6M
  size = sizeof(struct memdebug) + user_size;
254
255
33.6M
  mem = Curl_ccalloc(1, size);
256
33.6M
  if(mem)
257
33.6M
    mem->size = user_size;
258
259
33.6M
  if(source)
260
33.6M
    curl_dbg_log("MEM %s:%d calloc(%zu,%zu) = %p\n",
261
33.6M
                 source, line, wanted_elements, wanted_size,
262
33.6M
                 mem ? (void *)mem->mem : (void *)0);
263
264
33.6M
  return mem ? mem->mem : NULL;
265
33.6M
}
266
267
ALLOC_FUNC
268
char *curl_dbg_strdup(const char *str, int line, const char *source)
269
5.37M
{
270
5.37M
  char *mem;
271
5.37M
  size_t len;
272
273
5.37M
  DEBUGASSERT(str);
274
275
5.37M
  if(countcheck("strdup", line, source))
276
0
    return NULL;
277
278
5.37M
  len = strlen(str) + 1;
279
280
5.37M
  mem = curl_dbg_malloc(len, 0, NULL); /* NULL prevents logging */
281
5.37M
  if(mem)
282
5.36M
    memcpy(mem, str, len);
283
284
5.37M
  if(source)
285
5.37M
    curl_dbg_log("MEM %s:%d strdup(%p) (%zu) = %p\n",
286
5.37M
                 source, line, (const void *)str, len, (const void *)mem);
287
288
5.37M
  return mem;
289
5.37M
}
290
291
#if defined(_WIN32) && defined(UNICODE)
292
ALLOC_FUNC
293
wchar_t *curl_dbg_wcsdup(const wchar_t *str, int line, const char *source)
294
{
295
  wchar_t *mem;
296
  size_t wsiz, bsiz;
297
298
  DEBUGASSERT(str);
299
300
  if(countcheck("wcsdup", line, source))
301
    return NULL;
302
303
  wsiz = wcslen(str) + 1;
304
  bsiz = wsiz * sizeof(wchar_t);
305
306
  mem = curl_dbg_malloc(bsiz, 0, NULL); /* NULL prevents logging */
307
  if(mem)
308
    memcpy(mem, str, bsiz);
309
310
  if(source)
311
    curl_dbg_log("MEM %s:%d wcsdup(%p) (%zu) = %p\n",
312
                source, line, (const void *)str, bsiz, (void *)mem);
313
314
  return mem;
315
}
316
#endif
317
318
/* We provide a realloc() that accepts a NULL as pointer, which then
319
   performs a malloc(). In order to work with ares. */
320
void *curl_dbg_realloc(void *ptr, size_t wantedsize,
321
                       int line, const char *source)
322
15.8M
{
323
15.8M
  struct memdebug *mem = NULL;
324
15.8M
  bool was_locked;
325
326
15.8M
  size_t size = sizeof(struct memdebug) + wantedsize;
327
328
15.8M
  DEBUGASSERT(wantedsize != 0);
329
330
15.8M
  if(countcheck("realloc", line, source))
331
0
    return NULL;
332
333
  /* need to realloc under lock, as we get out-of-order log
334
   * entries otherwise, since another thread might alloc the
335
   * memory released by realloc() before otherwise would log it. */
336
15.8M
  was_locked = curl_dbg_lock();
337
#ifdef __INTEL_COMPILER
338
#  pragma warning(push)
339
#  pragma warning(disable:1684)
340
   /* 1684: conversion from pointer to same-sized integral type */
341
#endif
342
343
15.8M
  if(ptr)
344
2.85M
    mem = (void *)((char *)ptr - offsetof(struct memdebug, mem));
345
346
#ifdef __INTEL_COMPILER
347
#  pragma warning(pop)
348
#endif
349
350
15.8M
  mem = Curl_crealloc(mem, size);
351
15.8M
  if(source)
352
15.8M
    curl_dbg_log_locked("MEM %s:%d realloc(%p, %zu) = %p\n",
353
15.8M
                        source, line, (void *)ptr, wantedsize,
354
15.8M
                        mem ? (void *)mem->mem : (void *)0);
355
356
15.8M
  curl_dbg_unlock(was_locked);
357
15.8M
  if(mem) {
358
15.8M
    mem->size = wantedsize;
359
15.8M
    return mem->mem;
360
15.8M
  }
361
362
8.49k
  return NULL;
363
15.8M
}
364
365
void curl_dbg_free(void *ptr, int line, const char *source)
366
249M
{
367
249M
  if(ptr) {
368
65.9M
    struct memdebug *mem;
369
370
65.9M
    if(source)
371
65.9M
      curl_dbg_log("MEM %s:%d free(%p)\n", source, line, (void *)ptr);
372
373
#ifdef __INTEL_COMPILER
374
#  pragma warning(push)
375
#  pragma warning(disable:1684)
376
   /* 1684: conversion from pointer to same-sized integral type */
377
#endif
378
379
65.9M
    mem = (void *)((char *)ptr - offsetof(struct memdebug, mem));
380
381
#ifdef __INTEL_COMPILER
382
#  pragma warning(pop)
383
#endif
384
385
    /* free for real */
386
65.9M
    Curl_cfree(mem);
387
65.9M
  }
388
249M
}
389
390
curl_socket_t curl_dbg_socket(int domain, int type, int protocol,
391
                              int line, const char *source)
392
440k
{
393
440k
  curl_socket_t sockfd;
394
395
440k
  if(countcheck("socket", line, source))
396
0
    return CURL_SOCKET_BAD;
397
398
  /* !checksrc! disable BANNEDFUNC 1 */
399
440k
  sockfd = socket(domain, type, protocol);
400
401
440k
  if(source && (sockfd != CURL_SOCKET_BAD))
402
440k
    curl_dbg_log("FD %s:%d socket() = %" FMT_SOCKET_T "\n",
403
440k
                 source, line, sockfd);
404
405
440k
  return sockfd;
406
440k
}
407
408
#ifdef HAVE_SOCKETPAIR
409
int curl_dbg_socketpair(int domain, int type, int protocol,
410
                        curl_socket_t socket_vector[2],
411
                        int line, const char *source)
412
1.09k
{
413
  /* !checksrc! disable BANNEDFUNC 1 */
414
1.09k
  int res = socketpair(domain, type, protocol, socket_vector);
415
416
1.09k
  if(source && (res == 0))
417
271
    curl_dbg_log("FD %s:%d socketpair() = "
418
271
                 "%" FMT_SOCKET_T " %" FMT_SOCKET_T "\n",
419
271
                 source, line, socket_vector[0], socket_vector[1]);
420
421
1.09k
  return res;
422
1.09k
}
423
#endif
424
425
curl_socket_t curl_dbg_accept(curl_socket_t s, void *saddr, void *saddrlen,
426
                              int line, const char *source)
427
1.43k
{
428
1.43k
  struct sockaddr *addr = (struct sockaddr *)saddr;
429
1.43k
  curl_socklen_t *addrlen = (curl_socklen_t *)saddrlen;
430
431
  /* !checksrc! disable BANNEDFUNC 1 */
432
1.43k
  curl_socket_t sockfd = accept(s, addr, addrlen);
433
434
1.43k
  if(source && (sockfd != CURL_SOCKET_BAD))
435
0
    curl_dbg_log("FD %s:%d accept() = %" FMT_SOCKET_T "\n",
436
0
                 source, line, sockfd);
437
438
1.43k
  return sockfd;
439
1.43k
}
440
441
#ifdef HAVE_ACCEPT4
442
curl_socket_t curl_dbg_accept4(curl_socket_t s, void *saddr, void *saddrlen,
443
                               int flags,
444
                               int line, const char *source)
445
165
{
446
165
  struct sockaddr *addr = (struct sockaddr *)saddr;
447
165
  curl_socklen_t *addrlen = (curl_socklen_t *)saddrlen;
448
449
  /* !checksrc! disable BANNEDFUNC 1 */
450
165
  curl_socket_t sockfd = accept4(s, addr, addrlen, flags);
451
452
165
  if(source && (sockfd != CURL_SOCKET_BAD))
453
165
    curl_dbg_log("FD %s:%d accept() = %" FMT_SOCKET_T "\n",
454
165
                 source, line, sockfd);
455
456
165
  return sockfd;
457
165
}
458
#endif
459
460
/* separate function to allow libcurl to mark a "faked" close */
461
void curl_dbg_mark_sclose(curl_socket_t sockfd, int line, const char *source)
462
943k
{
463
943k
  if(source)
464
941k
    curl_dbg_log("FD %s:%d sclose(%" FMT_SOCKET_T ")\n",
465
941k
                 source, line, sockfd);
466
943k
}
467
468
/* this is our own defined way to close sockets on *ALL* platforms */
469
int curl_dbg_sclose(curl_socket_t sockfd, int line, const char *source)
470
943k
{
471
943k
  curl_dbg_mark_sclose(sockfd, line, source);
472
943k
  return CURL_SCLOSE(sockfd);
473
943k
}
474
475
ALLOC_FUNC
476
FILE *curl_dbg_fopen(const char *file, const char *mode,
477
                     int line, const char *source)
478
3.00M
{
479
3.00M
  FILE *res = CURLX_FOPEN_LOW(file, mode);
480
3.00M
  if(source)
481
3.00M
    curl_dbg_log("FILE %s:%d fopen(\"%s\",\"%s\") = %p\n",
482
3.00M
                 source, line, file, mode, (void *)res);
483
484
3.00M
  return res;
485
3.00M
}
486
487
ALLOC_FUNC
488
FILE *curl_dbg_freopen(const char *file, const char *mode, FILE *fh,
489
                       int line, const char *source)
490
649
{
491
649
  FILE *res = CURLX_FREOPEN_LOW(file, mode, fh);
492
649
  if(source)
493
424
    curl_dbg_log("FILE %s:%d freopen(\"%s\",\"%s\",%p) = %p\n",
494
424
                 source, line, file, mode, (void *)fh, (void *)res);
495
496
649
  return res;
497
649
}
498
499
ALLOC_FUNC
500
FILE *curl_dbg_fdopen(int filedes, const char *mode,
501
                      int line, const char *source)
502
548
{
503
548
  FILE *res = CURLX_FDOPEN_LOW(filedes, mode);
504
548
  if(source)
505
242
    curl_dbg_log("FILE %s:%d fdopen(\"%d\",\"%s\") = %p\n",
506
242
                 source, line, filedes, mode, (void *)res);
507
548
  return res;
508
548
}
509
510
int curl_dbg_fclose(FILE *file, int line, const char *source)
511
3.00M
{
512
3.00M
  int res;
513
514
3.00M
  DEBUGASSERT(file);
515
516
3.00M
  if(source)
517
3.00M
    curl_dbg_log("FILE %s:%d fclose(%p)\n", source, line, (void *)file);
518
519
  /* !checksrc! disable BANNEDFUNC 1 */
520
3.00M
  res = fclose(file);
521
522
3.00M
  return res;
523
3.00M
}
524
525
static void curl_dbg_vlog(const char * const fmt,
526
                          va_list ap) CURL_PRINTF(1, 0);
527
528
static void curl_dbg_vlog(const char * const fmt, va_list ap)
529
0
{
530
0
  char buf[1024];
531
0
  size_t nchars = curl_mvsnprintf(buf, sizeof(buf), fmt, ap);
532
533
0
  if(nchars > (int)sizeof(buf) - 1)
534
0
    nchars = (int)sizeof(buf) - 1;
535
536
0
  if(nchars > 0) {
537
0
    if(sizeof(membuf) - nchars < memwidx) {
538
      /* flush */
539
0
      fwrite(membuf, 1, memwidx, curl_dbg_logfile);
540
0
      fflush(curl_dbg_logfile);
541
0
      memwidx = 0;
542
0
    }
543
0
    if(memwidx) {
544
      /* the previous line ends with a newline */
545
0
      DEBUGASSERT(membuf[memwidx - 1] == '\n');
546
0
    }
547
0
    memcpy(&membuf[memwidx], buf, nchars);
548
0
    memwidx += nchars;
549
0
  }
550
0
}
551
552
static void curl_dbg_log_locked(const char *format, ...)
553
15.8M
{
554
15.8M
  va_list ap;
555
556
15.8M
  if(!curl_dbg_logfile)
557
15.8M
    return;
558
559
15.8M
  va_start(ap, format);
560
0
  curl_dbg_vlog(format, ap);
561
0
  va_end(ap);
562
0
}
563
564
/* this does the writing to the memory tracking log file */
565
void curl_dbg_log(const char *format, ...)
566
126M
{
567
126M
  bool was_locked;
568
126M
  va_list ap;
569
570
126M
  if(!curl_dbg_logfile)
571
126M
    return;
572
573
14
  was_locked = curl_dbg_lock();
574
14
  va_start(ap, format);
575
14
  curl_dbg_vlog(format, ap);
576
  va_end(ap);
577
14
  curl_dbg_unlock(was_locked);
578
14
}
579
580
#endif /* CURL_MEMDEBUG */