Coverage Report

Created: 2026-12-01 07:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/bind9/lib/isc/mem.c
Line
Count
Source
1
/*
2
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3
 *
4
 * SPDX-License-Identifier: MPL-2.0
5
 *
6
 * This Source Code Form is subject to the terms of the Mozilla Public
7
 * License, v. 2.0. If a copy of the MPL was not distributed with this
8
 * file, you can obtain one at https://mozilla.org/MPL/2.0/.
9
 *
10
 * See the COPYRIGHT file distributed with this work for additional
11
 * information regarding copyright ownership.
12
 */
13
14
/*! \file */
15
16
#include <inttypes.h>
17
#include <limits.h>
18
#include <stdbool.h>
19
#include <stddef.h>
20
#include <stdint.h>
21
#include <stdio.h>
22
#include <stdlib.h>
23
#include <unistd.h>
24
25
#include <isc/atomic.h>
26
#include <isc/backtrace.h>
27
#include <isc/hash.h>
28
#include <isc/magic.h>
29
#include <isc/mem.h>
30
#include <isc/mutex.h>
31
#include <isc/os.h>
32
#include <isc/overflow.h>
33
#include <isc/random.h>
34
#include <isc/refcount.h>
35
#include <isc/stdtime.h>
36
#include <isc/strerr.h>
37
#include <isc/string.h>
38
#include <isc/tid.h>
39
#include <isc/types.h>
40
#include <isc/urcu.h>
41
#include <isc/util.h>
42
#include <isc/uv.h>
43
44
#ifdef HAVE_LIBXML2
45
#include <libxml/xmlwriter.h>
46
#define ISC_XMLCHAR (const xmlChar *)
47
#endif /* HAVE_LIBXML2 */
48
49
#ifdef HAVE_JSON_C
50
#include <json_object.h>
51
#endif /* HAVE_JSON_C */
52
53
/* On DragonFly BSD the header does not provide jemalloc API */
54
#if defined(HAVE_MALLOC_NP_H) && !defined(__DragonFly__)
55
#include <malloc_np.h>
56
#define JEMALLOC_API_SUPPORTED 1
57
#elif defined(HAVE_JEMALLOC)
58
#include <jemalloc/jemalloc.h>
59
#define JEMALLOC_API_SUPPORTED 1
60
#else
61
#if defined(__GLIBC__)
62
#include <malloc.h>
63
#endif
64
#include "jemalloc_shim.h"
65
#endif
66
67
#include "mem_p.h"
68
69
92.6k
#define MCTXLOCK(m)   LOCK(&m->lock)
70
92.6k
#define MCTXUNLOCK(m) UNLOCK(&m->lock)
71
72
#ifndef ISC_MEM_DEBUGGING
73
#define ISC_MEM_DEBUGGING 0
74
#endif /* ifndef ISC_MEM_DEBUGGING */
75
76
static unsigned int mem_debugging = ISC_MEM_DEBUGGING;
77
78
volatile void *isc__mem_malloc = mallocx;
79
80
isc_mem_t *isc_g_mctx = NULL;
81
82
/*
83
 * Constants.
84
 */
85
86
4
#define ZERO_ALLOCATION_SIZE sizeof(void *)
87
#define DEBUG_TABLE_COUNT    512U
88
89
#ifdef JEMALLOC_API_SUPPORTED
90
static ssize_t default_dirty_decay_ms = 10000;
91
#endif
92
93
/*
94
 * Types.
95
 */
96
#if ISC_MEM_TRACKLINES
97
typedef struct debuglink debuglink_t;
98
struct debuglink {
99
  size_t dlsize;
100
  ISC_LINK(debuglink_t) link;
101
  const void *ptr;
102
  size_t size;
103
  unsigned int line;
104
  const char file[];
105
};
106
107
typedef ISC_LIST(debuglink_t) debuglist_t;
108
109
#define FLARG_PASS , func, file, line
110
#define FLARG    , const char *func, const char *file, unsigned int line
111
#else /* if ISC_MEM_TRACKLINES */
112
#define FLARG_PASS
113
#define FLARG
114
#endif /* if ISC_MEM_TRACKLINES */
115
116
typedef struct element element;
117
struct element {
118
  element *next;
119
};
120
121
34.8k
#define MEM_MAGIC  ISC_MAGIC('M', 'e', 'm', 'C')
122
#define VALID_CONTEXT(c) ISC_MAGIC_VALID(c, MEM_MAGIC)
123
124
/* List of all active memory contexts. */
125
126
static ISC_LIST(isc_mem_t) contexts;
127
128
static isc_mutex_t contextslock;
129
130
typedef union {
131
  struct {
132
    atomic_int_fast64_t inuse;
133
  };
134
  char padding[ISC_OS_CACHELINE_SIZE];
135
} isc__mem_stat_t;
136
137
struct isc_mem {
138
  unsigned int magic;
139
  unsigned int jemalloc_flags;
140
  unsigned int debugging;
141
  isc_mutex_t lock;
142
  bool checkfree;
143
  isc_refcount_t references;
144
  char *name;
145
  atomic_size_t hi_water;
146
  atomic_size_t lo_water;
147
  ISC_LIST(isc_mempool_t) pools;
148
  unsigned int poolcnt;
149
150
#if ISC_MEM_TRACKLINES
151
  debuglist_t *debuglist;
152
  size_t debuglistcnt;
153
#endif /* if ISC_MEM_TRACKLINES */
154
155
  ISC_LINK(isc_mem_t) link;
156
157
  isc__mem_stat_t *stat;
158
  isc__mem_stat_t stat_s[ISC_TID_MAX + 1];
159
};
160
161
45.8k
#define MEMPOOL_MAGIC  ISC_MAGIC('M', 'E', 'M', 'p')
162
#define VALID_MEMPOOL(c) ISC_MAGIC_VALID(c, MEMPOOL_MAGIC)
163
164
struct isc_mempool {
165
  /* always unlocked */
166
  unsigned int magic;
167
  isc_mem_t *mctx;        /*%< our memory context */
168
  ISC_LINK(isc_mempool_t) link; /*%< next pool in this mem context */
169
  element *items;         /*%< low water item list */
170
  size_t size;          /*%< size of each item on this pool */
171
  size_t allocated;       /*%< # of items currently given out */
172
  size_t freecount;       /*%< # of items on reserved list */
173
  size_t freemax;         /*%< # of items allowed on free list */
174
  size_t fillcount;       /*%< # of items to fetch on each fill */
175
  /*%< Stats only. */
176
  size_t gets; /*%< # of requests to this pool */
177
  /*%< Debugging only. */
178
  char *name; /*%< printed name in stats reports */
179
};
180
181
/*
182
 * Private Inline-able.
183
 */
184
185
static size_t
186
0
total_inuse(void) {
187
0
  size_t inuse = 0;
188
0
  LOCK(&contextslock);
189
0
  ISC_LIST_FOREACH(contexts, ctx, link) {
190
0
    inuse += isc_mem_inuse(ctx);
191
0
  }
192
0
  UNLOCK(&contextslock);
193
194
0
  return inuse;
195
0
}
196
197
static void
198
0
write_string(int fd, const char *str) {
199
0
  int r = write(fd, str, strlen(str));
200
0
  if (r == -1) {
201
0
    abort();
202
0
  }
203
0
}
204
205
#define STRINGIFY(x) #x
206
#define TOSTRING(x)  STRINGIFY(x)
207
static void
208
0
write_size(int fd, size_t size) {
209
0
  char buf[sizeof(TOSTRING(SIZE_MAX)) + 1] = { 0 };
210
211
0
  char *str = buf + (sizeof(buf) - 1);
212
213
0
  if (size == 0) {
214
0
    *--str = '0';
215
0
  } else {
216
0
    while (size) {
217
0
      *--str = '0' + (size % 10);
218
0
      size /= 10;
219
0
    }
220
0
  }
221
222
0
  write_string(fd, str);
223
0
}
224
225
static void
226
0
write_errno(int fd, int errnum) {
227
0
  char buf[BUFSIZ] = { 0 };
228
0
  int ret = isc_string_strerror_r(errnum, buf, sizeof(buf));
229
0
  if (ret == 0) {
230
0
    write_string(fd, buf);
231
0
  }
232
0
}
233
234
static void
235
0
write_backtrace(int fd) {
236
0
  void *tracebuf[ISC_BACKTRACE_MAXFRAME];
237
0
  int nframes = isc_backtrace(tracebuf, ISC_BACKTRACE_MAXFRAME);
238
239
0
  if (nframes > 0) {
240
0
    isc_backtrace_symbols_fd(tracebuf, nframes, fd);
241
0
  }
242
0
}
243
244
111M
#define CHECK_OOM(ptr, size) (void)((ptr != NULL) || (oom(size), false))
245
246
ISC_NORETURN static void
247
0
oom(size_t size) {
248
0
  int fd = fileno(stderr);
249
0
  write_string(fd, "Out of memory (trying to allocate ");
250
0
  write_size(fd, size);
251
0
  write_string(fd, ", total ");
252
0
  write_size(fd, total_inuse());
253
0
  write_string(fd, "): ");
254
0
  write_errno(fd, errno);
255
0
  write_string(fd, "\n");
256
0
  write_backtrace(fd);
257
258
0
  abort();
259
0
}
260
261
#if !ISC_MEM_TRACKLINES
262
#define ADD_TRACE(mctx, ptr, size, func, file, line)
263
#define DELETE_TRACE(mctx, ptr, size, func, file, line)
264
#define ISC_MEMFUNC_SCOPE
265
#else /* if !ISC_MEM_TRACKLINES */
266
#define TRACE_OR_RECORD (ISC_MEM_DEBUGTRACE | ISC_MEM_DEBUGRECORD)
267
268
#define SHOULD_TRACE_OR_RECORD(mctx, ptr) \
269
  (((mctx)->debugging & TRACE_OR_RECORD) != 0 && ptr != NULL)
270
271
#define ADD_TRACE(mctx, ptr, size, func, file, line)                \
272
  if (SHOULD_TRACE_OR_RECORD(mctx, ptr)) {                    \
273
    add_trace_entry(mctx, ptr, size, func, file, line); \
274
  }
275
276
#define DELETE_TRACE(mctx, ptr, size, func, file, line)                \
277
  if (SHOULD_TRACE_OR_RECORD(mctx, ptr)) {                       \
278
    delete_trace_entry(mctx, ptr, size, func, file, line); \
279
  }
280
281
static void
282
print_active(isc_mem_t *ctx, FILE *out);
283
#endif /* ISC_MEM_TRACKLINES */
284
285
#if ISC_MEM_TRACKLINES
286
/*!
287
 * mctx must not be locked.
288
 */
289
static void
290
add_trace_entry(isc_mem_t *mctx, const void *ptr, size_t size FLARG) {
291
  debuglink_t *dl = NULL;
292
  uint32_t hash;
293
  uint32_t idx;
294
295
  /*
296
   * "file" needs to be copied because it can be part of a dynamically
297
   * loaded plugin which would be unloaded at the time the trace is
298
   * dumped. Storing "file" pointer then leads to a dangling pointer
299
   * dereference and a crash.
300
   */
301
  size_t filelen = strlen(file) + 1;
302
  size_t dlsize = STRUCT_FLEX_SIZE(dl, file, filelen);
303
304
  MCTXLOCK(mctx);
305
306
  if ((mctx->debugging & ISC_MEM_DEBUGTRACE) != 0) {
307
    fprintf(stderr,
308
      "add %p size %zu func %s file %s line %u mctx %p\n",
309
      ptr, size, func, file, line, mctx);
310
  }
311
312
  if (mctx->debuglist == NULL) {
313
    goto unlock;
314
  }
315
316
  hash = isc_hash32(&ptr, sizeof(ptr), true);
317
  idx = hash % DEBUG_TABLE_COUNT;
318
319
  dl = mallocx(dlsize, mctx->jemalloc_flags);
320
  CHECK_OOM(dl, dlsize);
321
322
  ISC_LINK_INIT(dl, link);
323
  dl->ptr = ptr;
324
  dl->size = size;
325
  dl->line = line;
326
  dl->dlsize = dlsize;
327
  strlcpy((char *)dl->file, file, filelen);
328
329
  ISC_LIST_PREPEND(mctx->debuglist[idx], dl, link);
330
  mctx->debuglistcnt++;
331
unlock:
332
  MCTXUNLOCK(mctx);
333
}
334
335
static void
336
delete_trace_entry(isc_mem_t *mctx, const void *ptr, size_t size FLARG) {
337
  uint32_t hash;
338
  uint32_t idx;
339
340
  MCTXLOCK(mctx);
341
342
  if ((mctx->debugging & ISC_MEM_DEBUGTRACE) != 0) {
343
    fprintf(stderr,
344
      "del %p size %zu func %s file %s line %u mctx %p\n",
345
      ptr, size, func, file, line, mctx);
346
  }
347
348
  if (mctx->debuglist == NULL) {
349
    goto unlock;
350
  }
351
352
  hash = isc_hash32(&ptr, sizeof(ptr), true);
353
  idx = hash % DEBUG_TABLE_COUNT;
354
355
  ISC_LIST_FOREACH(mctx->debuglist[idx], dl, link) {
356
    if (dl->ptr == ptr) {
357
      ISC_LIST_UNLINK(mctx->debuglist[idx], dl, link);
358
      sdallocx(dl, dl->dlsize, mctx->jemalloc_flags);
359
      goto unlock;
360
    }
361
  }
362
363
  /*
364
   * If we get here, we didn't find the item on the list.  We're
365
   * screwed.
366
   */
367
  UNREACHABLE();
368
unlock:
369
  MCTXUNLOCK(mctx);
370
}
371
#endif /* ISC_MEM_TRACKLINES */
372
373
#define ADJUST_ZERO_ALLOCATION_SIZE(s)    \
374
223M
  if (s == 0) {                     \
375
4
    s = ZERO_ALLOCATION_SIZE; \
376
4
  }
377
378
/*!
379
 * Perform a malloc, doing memory filling and overrun detection as necessary.
380
 */
381
static void *
382
111M
mem_get(isc_mem_t *ctx, size_t size, int flags) {
383
111M
  ADJUST_ZERO_ALLOCATION_SIZE(size);
384
385
111M
  void *ptr = mallocx(size, flags | ctx->jemalloc_flags);
386
111M
  CHECK_OOM(ptr, size);
387
388
111M
  return ptr;
389
111M
}
390
391
static thread_local size_t freed_bytes = 0;
392
393
constexpr size_t purge_threshold = (16 * 1024 * 1024);
394
395
#if defined(JEMALLOC_API_SUPPORTED) || defined(__GLIBC__)
396
397
static _Atomic(isc_stdtime_t) last_purge = 0;
398
399
static void
400
5.45k
mem_purge(void) {
401
5.45k
  isc_stdtime_t now = isc_stdtime_now();
402
5.45k
  isc_stdtime_t last = atomic_load_relaxed(&last_purge);
403
404
5.45k
  if (now > last &&
405
5.45k
      atomic_compare_exchange_strong_acq_rel(&last_purge, &last, now))
406
119
  {
407
#if defined(JEMALLOC_API_SUPPORTED)
408
    (void)mallctl("arena." STRINGIFY(MALLCTL_ARENAS_ALL) ".decay",
409
            NULL, NULL, NULL, 0);
410
#elif defined(__GLIBC__)
411
    (void)malloc_trim(0);
412
119
#endif
413
119
  }
414
5.45k
}
415
416
#else
417
static void
418
mem_purge(void) {
419
  /* no-op */
420
}
421
422
#endif
423
424
/*!
425
 * Perform a free, doing memory filling and overrun detection as necessary.
426
 */
427
static void
428
111M
mem_put(isc_mem_t *ctx, void *mem, size_t size, int flags) {
429
111M
  ADJUST_ZERO_ALLOCATION_SIZE(size);
430
431
111M
  sdallocx(mem, size, flags | ctx->jemalloc_flags);
432
433
111M
  freed_bytes += size;
434
435
111M
  if (freed_bytes >= purge_threshold) {
436
5.45k
    freed_bytes = 0;
437
5.45k
    mem_purge();
438
5.45k
  }
439
111M
}
440
441
static void *
442
10.1k
mem_realloc(isc_mem_t *ctx, void *old_ptr, size_t new_size, int flags) {
443
10.1k
  void *new_ptr = NULL;
444
445
10.1k
  ADJUST_ZERO_ALLOCATION_SIZE(new_size);
446
447
10.1k
  new_ptr = rallocx(old_ptr, new_size, flags | ctx->jemalloc_flags);
448
10.1k
  CHECK_OOM(new_ptr, new_size);
449
450
10.1k
  return new_ptr;
451
10.1k
}
452
453
/*!
454
 * Update internal counters after a memory get.
455
 */
456
static void
457
111M
mem_getstats(isc_mem_t *ctx, size_t size) {
458
111M
  atomic_fetch_add_relaxed(&ctx->stat[isc_tid()].inuse, size);
459
111M
}
460
461
/*!
462
 * Update internal counters after a memory put.
463
 */
464
static void
465
111M
mem_putstats(isc_mem_t *ctx, size_t size) {
466
111M
  atomic_fetch_sub_relaxed(&ctx->stat[isc_tid()].inuse, size);
467
111M
}
468
469
/*
470
 * Private.
471
 */
472
473
static bool
474
66
debugging_enabled(const char *name) {
475
66
  char env_buf[256];
476
66
  size_t env_size = sizeof(env_buf);
477
478
66
  int r = uv_os_getenv(name, env_buf, &env_size);
479
66
  switch (r) {
480
0
  case 0:
481
0
    return true;
482
66
  case UV_ENOENT:
483
66
    return false;
484
0
  default:
485
0
    UV_RUNTIME_CHECK(uv_os_getenv, r);
486
0
    UNREACHABLE();
487
66
  }
488
66
}
489
490
void
491
22
isc__mem_initialize(void) {
492
  /*
493
   * Check if the values copied from jemalloc still match; the
494
   * shim defines the MALLOCX_* macros too, so this holds on
495
   * every allocator path.
496
   */
497
22
  RUNTIME_CHECK(ISC_MEM_ZERO == MALLOCX_ZERO);
498
22
  RUNTIME_CHECK(ISC_MEM_ALIGN(sizeof(void *)) ==
499
22
          MALLOCX_ALIGN(sizeof(void *)));
500
22
  RUNTIME_CHECK(ISC_MEM_ALIGN(ISC_OS_CACHELINE_SIZE) ==
501
22
          MALLOCX_ALIGN(ISC_OS_CACHELINE_SIZE));
502
503
#ifdef JEMALLOC_API_SUPPORTED
504
  /*
505
   * ignore errors — volumetric-based purge in mem_put handles the rest
506
   * regardless
507
   */
508
509
  (void)mallctl("background_thread", NULL, NULL, &(bool){ true },
510
          sizeof(bool));
511
512
  (void)mallctl("arenas.dirty_decay_ms", NULL, NULL,
513
          &default_dirty_decay_ms, sizeof(default_dirty_decay_ms));
514
515
  (void)mallctl("arena." STRINGIFY(MALLCTL_ARENAS_ALL) ".dirty_decay_ms",
516
          NULL, NULL, &default_dirty_decay_ms,
517
          sizeof(default_dirty_decay_ms));
518
519
#endif /* JEMALLOC_API_SUPPORTED */
520
521
22
  isc_mutex_init(&contextslock);
522
22
  ISC_LIST_INIT(contexts);
523
524
22
  if (debugging_enabled("ISC_MEM_DEBUGTRACE")) {
525
0
    mem_debugging |= ISC_MEM_DEBUGTRACE;
526
0
  }
527
528
22
  if (debugging_enabled("ISC_MEM_DEBUGRECORD")) {
529
0
    mem_debugging |= ISC_MEM_DEBUGRECORD;
530
0
  }
531
532
22
  if (debugging_enabled("ISC_MEM_DEBUGUSAGE")) {
533
0
    mem_debugging |= ISC_MEM_DEBUGUSAGE;
534
0
  }
535
536
22
  isc_mem_create("default", &isc_g_mctx);
537
22
}
538
539
void
540
0
isc__mem_shutdown(void) {
541
0
  bool empty;
542
543
0
  rcu_barrier();
544
545
0
  isc_mem_detach(&isc_g_mctx);
546
547
0
  isc__mem_checkdestroyed();
548
549
0
  LOCK(&contextslock);
550
0
  empty = ISC_LIST_EMPTY(contexts);
551
0
  UNLOCK(&contextslock);
552
553
0
  if (empty) {
554
0
    isc_mutex_destroy(&contextslock);
555
0
  }
556
0
}
557
558
void
559
44
isc_mem_setdebugging(isc_mem_t *ctx, unsigned int debugging) {
560
44
  REQUIRE(VALID_CONTEXT(ctx));
561
44
  REQUIRE(isc_mem_inuse(ctx) == 0);
562
563
44
  ctx->debugging = debugging;
564
44
}
565
566
unsigned int
567
0
isc_mem_debugon(unsigned int debugging) {
568
0
  unsigned int old_mem_debugging = mem_debugging;
569
570
0
  if (debugging != 0) {
571
0
    mem_debugging |= debugging;
572
573
0
    isc_mem_setdebugging(isc_g_mctx, mem_debugging);
574
0
  }
575
576
0
  return old_mem_debugging;
577
0
}
578
579
unsigned int
580
0
isc_mem_debugoff(unsigned int debugging) {
581
0
  unsigned int old_mem_debugging = mem_debugging;
582
583
0
  if (debugging != 0) {
584
0
    mem_debugging &= ~debugging;
585
586
0
    isc_mem_setdebugging(isc_g_mctx, mem_debugging);
587
0
  }
588
589
0
  return old_mem_debugging;
590
0
}
591
592
static void
593
mem_create(const char *name, isc_mem_t **ctxp, unsigned int debugging,
594
34.8k
     unsigned int jemalloc_flags) {
595
34.8k
  isc_mem_t *ctx = NULL;
596
597
34.8k
  REQUIRE(ctxp != NULL && *ctxp == NULL);
598
34.8k
  REQUIRE(name != NULL);
599
600
34.8k
  ctx = mallocx(sizeof(*ctx),
601
34.8k
          jemalloc_flags | ISC_MEM_ALIGN(isc_os_cacheline()));
602
34.8k
  CHECK_OOM(ctx, sizeof(*ctx));
603
604
34.8k
  *ctx = (isc_mem_t){
605
34.8k
    .magic = MEM_MAGIC,
606
34.8k
    .debugging = debugging,
607
34.8k
    .jemalloc_flags = jemalloc_flags,
608
34.8k
    .checkfree = true,
609
34.8k
    .name = strdup(name),
610
34.8k
  };
611
612
34.8k
  isc_mutex_init(&ctx->lock);
613
34.8k
  isc_refcount_init(&ctx->references, 1);
614
615
17.9M
  for (size_t i = 0; i < ARRAY_SIZE(ctx->stat_s); i++) {
616
17.8M
    atomic_init(&ctx->stat_s[i].inuse, 0);
617
17.8M
  }
618
619
  /* Reserve the [-1] index for ISC_TID_UNKNOWN */
620
34.8k
  ctx->stat = &ctx->stat_s[1];
621
622
34.8k
  atomic_init(&ctx->hi_water, 0);
623
34.8k
  atomic_init(&ctx->lo_water, 0);
624
625
34.8k
  ISC_LIST_INIT(ctx->pools);
626
627
#if ISC_MEM_TRACKLINES
628
  if ((ctx->debugging & ISC_MEM_DEBUGRECORD) != 0) {
629
    unsigned int i;
630
    size_t debuglist_size = ISC_CHECKED_MUL(DEBUG_TABLE_COUNT,
631
              sizeof(debuglist_t));
632
633
    ctx->debuglist = mallocx(debuglist_size, jemalloc_flags);
634
    CHECK_OOM(ctx->debuglist, debuglist_size);
635
636
    for (i = 0; i < DEBUG_TABLE_COUNT; i++) {
637
      ISC_LIST_INIT(ctx->debuglist[i]);
638
    }
639
  }
640
#endif /* if ISC_MEM_TRACKLINES */
641
642
34.8k
  LOCK(&contextslock);
643
34.8k
  ISC_LIST_INITANDAPPEND(contexts, ctx, link);
644
34.8k
  UNLOCK(&contextslock);
645
646
34.8k
  *ctxp = ctx;
647
34.8k
}
648
649
/*
650
 * Public.
651
 */
652
653
static void
654
34.7k
mem_destroy(isc_mem_t *ctx) {
655
34.7k
  REQUIRE(VALID_CONTEXT(ctx));
656
657
34.7k
  isc_refcount_destroy(&ctx->references);
658
659
34.7k
  LOCK(&contextslock);
660
34.7k
  ISC_LIST_UNLINK(contexts, ctx, link);
661
34.7k
  UNLOCK(&contextslock);
662
663
#if ISC_MEM_TRACKLINES
664
  if (ctx->debuglist != NULL) {
665
    for (size_t i = 0; i < DEBUG_TABLE_COUNT; i++) {
666
      ISC_LIST_FOREACH(ctx->debuglist[i], dl, link) {
667
        if (ctx->checkfree && dl->ptr != NULL) {
668
          print_active(ctx, stderr);
669
        }
670
        INSIST(!ctx->checkfree || dl->ptr == NULL);
671
672
        ISC_LIST_UNLINK(ctx->debuglist[i], dl, link);
673
        sdallocx(dl, dl->dlsize, ctx->jemalloc_flags);
674
      }
675
    }
676
677
    sdallocx(
678
      ctx->debuglist,
679
      ISC_CHECKED_MUL(DEBUG_TABLE_COUNT, sizeof(debuglist_t)),
680
      ctx->jemalloc_flags);
681
  }
682
#endif /* if ISC_MEM_TRACKLINES */
683
684
34.7k
  if (ctx->checkfree) {
685
34.7k
    INSIST(isc_mem_inuse(ctx) == 0);
686
34.7k
  }
687
688
34.7k
  ctx->magic = 0;
689
690
34.7k
  INSIST(ISC_LIST_EMPTY(ctx->pools));
691
692
34.7k
  free(ctx->name);
693
694
34.7k
  isc_mutex_destroy(&ctx->lock);
695
696
#if ISC_MEM_TRACKLINES
697
  if ((mem_debugging & ISC_MEM_DEBUGTRACE) != 0) {
698
    fprintf(stderr, "destroyed mctx %p\n", ctx);
699
  }
700
#endif /* ISC_MEM_TRACKLINES */
701
702
34.7k
  sdallocx(ctx, sizeof(*ctx),
703
34.7k
     ctx->jemalloc_flags | ISC_MEM_ALIGN(isc_os_cacheline()));
704
34.7k
}
705
706
#if ISC_MEM_TRACE
707
ISC_REFCOUNT_TRACE_IMPL(isc_mem, mem_destroy);
708
#else
709
49.5M
ISC_REFCOUNT_IMPL(isc_mem, mem_destroy);
isc_mem_ref
Line
Count
Source
709
ISC_REFCOUNT_IMPL(isc_mem, mem_destroy);
isc_mem_unref
Line
Count
Source
709
ISC_REFCOUNT_IMPL(isc_mem, mem_destroy);
isc_mem_detach
Line
Count
Source
709
ISC_REFCOUNT_IMPL(isc_mem, mem_destroy);
710
49.5M
#endif
711
49.5M
712
49.5M
/*
713
49.5M
 * isc_mem_putanddetach() is the equivalent of:
714
49.5M
 *
715
49.5M
 * mctx = NULL;
716
49.5M
 * isc_mem_attach(ptr->mctx, &mctx);
717
49.5M
 * isc_mem_detach(&ptr->mctx);
718
49.5M
 * isc_mem_put(mctx, ptr, sizeof(*ptr);
719
49.5M
 * isc_mem_detach(&mctx);
720
49.5M
 */
721
49.5M
722
49.5M
void
723
49.5M
isc__mem_putanddetach(isc_mem_t **ctxp, void *ptr, size_t size,
724
49.5M
          int flags FLARG) {
725
16.4M
  REQUIRE(ctxp != NULL && VALID_CONTEXT(*ctxp));
726
16.4M
  REQUIRE(ptr != NULL);
727
16.4M
  REQUIRE(size != 0);
728
729
16.4M
  isc_mem_t *ctx = *ctxp;
730
16.4M
  *ctxp = NULL;
731
732
16.4M
  isc__mem_put(ctx, ptr, size, flags FLARG_PASS);
733
#if ISC_MEM_TRACE
734
  isc_mem__detach(&ctx, func, file, line);
735
#else
736
16.4M
  isc_mem_detach(&ctx);
737
16.4M
#endif
738
16.4M
}
739
740
void *
741
57.0M
isc__mem_get(isc_mem_t *ctx, size_t size, int flags FLARG) {
742
57.0M
  void *ptr = NULL;
743
744
57.0M
  REQUIRE(VALID_CONTEXT(ctx));
745
746
57.0M
  ptr = mem_get(ctx, size, flags);
747
748
57.0M
  mem_getstats(ctx, size);
749
57.0M
  ADD_TRACE(ctx, ptr, size, func, file, line);
750
751
57.0M
  return ptr;
752
57.0M
}
753
754
void
755
56.6M
isc__mem_put(isc_mem_t *ctx, void *ptr, size_t size, int flags FLARG) {
756
56.6M
  REQUIRE(VALID_CONTEXT(ctx));
757
758
56.6M
  DELETE_TRACE(ctx, ptr, size, func, file, line);
759
760
56.6M
  mem_putstats(ctx, size);
761
56.6M
  mem_put(ctx, ptr, size, flags);
762
56.6M
}
763
764
#if ISC_MEM_TRACKLINES
765
static void
766
print_active(isc_mem_t *mctx, FILE *out) {
767
  if (mctx->debuglist != NULL) {
768
    unsigned int i;
769
    bool found;
770
771
    fprintf(out, "Dump of all outstanding memory "
772
           "allocations:\n");
773
    found = false;
774
    for (i = 0; i < DEBUG_TABLE_COUNT; i++) {
775
      ISC_LIST_FOREACH(mctx->debuglist[i], dl, link) {
776
        found = true;
777
        if (dl->ptr != NULL) {
778
          fprintf(out,
779
            "\tptr %p size %zu "
780
            "file %s "
781
            "line %u\n",
782
            dl->ptr, dl->size, dl->file,
783
            dl->line);
784
        }
785
      }
786
    }
787
788
    if (!found) {
789
      fprintf(out, "\tNone.\n");
790
    }
791
  }
792
}
793
#endif /* if ISC_MEM_TRACKLINES */
794
795
/*
796
 * Print the stats[] on the stream "out" with suitable formatting.
797
 */
798
void
799
0
isc_mem_stats(isc_mem_t *ctx, FILE *out) {
800
0
  REQUIRE(VALID_CONTEXT(ctx));
801
802
0
  MCTXLOCK(ctx);
803
804
  /*
805
   * Note that since a pool can be locked now, these stats might
806
   * be somewhat off if the pool is in active use at the time the
807
   * stats are dumped.  The link fields are protected by the
808
   * isc_mem_t's lock, however, so walking this list and
809
   * extracting integers from stats fields is always safe.
810
   */
811
0
  if (!ISC_LIST_EMPTY(ctx->pools)) {
812
0
    fprintf(out, "[Pool statistics]\n");
813
0
    fprintf(out, "%15s %10s %10s %10s %10s %10s %10s %1s\n", "name",
814
0
      "size", "allocated", "freecount", "freemax",
815
0
      "fillcount", "gets", "L");
816
0
  }
817
0
  ISC_LIST_FOREACH(ctx->pools, pool, link) {
818
0
    fprintf(out,
819
0
      "%15s %10zu %10zu %10zu %10zu %10zu %10zu %10zu %s\n",
820
0
      pool->name, pool->size, (size_t)0, pool->allocated,
821
0
      pool->freecount, pool->freemax, pool->fillcount,
822
0
      pool->gets, "N");
823
0
  }
824
825
#if ISC_MEM_TRACKLINES
826
  print_active(ctx, out);
827
#endif /* if ISC_MEM_TRACKLINES */
828
829
0
  MCTXUNLOCK(ctx);
830
0
}
831
832
void *
833
10.0M
isc__mem_allocate(isc_mem_t *ctx, size_t size, int flags FLARG) {
834
10.0M
  void *ptr = NULL;
835
836
10.0M
  REQUIRE(VALID_CONTEXT(ctx));
837
838
10.0M
  ptr = mem_get(ctx, size, flags);
839
840
  /* Recalculate the real allocated size */
841
10.0M
  size = sallocx(ptr, flags | ctx->jemalloc_flags);
842
843
10.0M
  mem_getstats(ctx, size);
844
10.0M
  ADD_TRACE(ctx, ptr, size, func, file, line);
845
846
10.0M
  return ptr;
847
10.0M
}
848
849
void *
850
isc__mem_reget(isc_mem_t *ctx, void *old_ptr, size_t old_size, size_t new_size,
851
0
         int flags FLARG) {
852
0
  void *new_ptr = NULL;
853
854
0
  if (old_ptr == NULL) {
855
0
    REQUIRE(old_size == 0);
856
0
    new_ptr = isc__mem_get(ctx, new_size, flags FLARG_PASS);
857
0
  } else if (new_size == 0) {
858
0
    isc__mem_put(ctx, old_ptr, old_size, flags FLARG_PASS);
859
0
  } else {
860
0
    DELETE_TRACE(ctx, old_ptr, old_size, func, file, line);
861
0
    mem_putstats(ctx, old_size);
862
863
0
    ADJUST_ZERO_ALLOCATION_SIZE(new_size);
864
865
0
    new_ptr = mem_realloc(ctx, old_ptr, new_size, flags);
866
867
0
    mem_getstats(ctx, new_size);
868
0
    ADD_TRACE(ctx, new_ptr, new_size, func, file, line);
869
870
    /*
871
     * We want to postpone the call to water in edge case
872
     * where the realloc will exactly hit on the boundary of
873
     * the water and we would call water twice.
874
     */
875
0
  }
876
877
0
  return new_ptr;
878
0
}
879
880
void *
881
isc__mem_reallocate(isc_mem_t *ctx, void *old_ptr, size_t new_size,
882
47.0k
        int flags FLARG) {
883
47.0k
  void *new_ptr = NULL;
884
885
47.0k
  REQUIRE(VALID_CONTEXT(ctx));
886
887
47.0k
  if (old_ptr == NULL) {
888
36.8k
    new_ptr = isc__mem_allocate(ctx, new_size, flags FLARG_PASS);
889
36.8k
  } else if (new_size == 0) {
890
0
    isc__mem_free(ctx, old_ptr, flags FLARG_PASS);
891
10.1k
  } else {
892
10.1k
    size_t size = sallocx(old_ptr, flags | ctx->jemalloc_flags);
893
894
10.1k
    DELETE_TRACE(ctx, old_ptr, size, func, file, line);
895
10.1k
    mem_putstats(ctx, size);
896
897
10.1k
    new_ptr = mem_realloc(ctx, old_ptr, new_size, flags);
898
899
    /* Recalculate the real allocated size */
900
10.1k
    size = sallocx(new_ptr, flags | ctx->jemalloc_flags);
901
902
10.1k
    mem_getstats(ctx, size);
903
10.1k
    ADD_TRACE(ctx, new_ptr, size, func, file, line);
904
10.1k
  }
905
906
47.0k
  return new_ptr;
907
47.0k
}
908
909
void
910
10.0M
isc__mem_free(isc_mem_t *ctx, void *ptr, int flags FLARG) {
911
10.0M
  size_t size = 0;
912
913
10.0M
  REQUIRE(VALID_CONTEXT(ctx));
914
10.0M
  REQUIRE(ptr != NULL);
915
916
10.0M
  size = sallocx(ptr, flags | ctx->jemalloc_flags);
917
918
10.0M
  DELETE_TRACE(ctx, ptr, size, func, file, line);
919
920
10.0M
  mem_putstats(ctx, size);
921
10.0M
  mem_put(ctx, ptr, size, flags);
922
10.0M
}
923
924
/*
925
 * Other useful things.
926
 */
927
928
char *
929
8.30M
isc__mem_strdup(isc_mem_t *mctx, const char *s FLARG) {
930
8.30M
  size_t len;
931
8.30M
  char *ns = NULL;
932
933
8.30M
  REQUIRE(VALID_CONTEXT(mctx));
934
8.30M
  REQUIRE(s != NULL);
935
936
8.30M
  len = strlen(s) + 1;
937
938
8.30M
  ns = isc__mem_allocate(mctx, len, 0 FLARG_PASS);
939
940
8.30M
  strlcpy(ns, s, len);
941
942
8.30M
  return ns;
943
8.30M
}
944
945
void
946
1.02k
isc_mem_setdestroycheck(isc_mem_t *ctx, bool flag) {
947
1.02k
  REQUIRE(VALID_CONTEXT(ctx));
948
949
1.02k
  MCTXLOCK(ctx);
950
951
1.02k
  ctx->checkfree = flag;
952
953
1.02k
  MCTXUNLOCK(ctx);
954
1.02k
}
955
956
size_t
957
34.7k
isc_mem_inuse(isc_mem_t *ctx) {
958
34.7k
  REQUIRE(VALID_CONTEXT(ctx));
959
960
34.7k
  int_fast64_t inuse = 0;
961
962
69.5k
  for (ssize_t i = -1; i < isc_tid_count(); i++) {
963
34.7k
    inuse += atomic_load_relaxed(&ctx->stat[i].inuse);
964
34.7k
  }
965
34.7k
  INSIST(inuse >= 0);
966
967
34.7k
  return (size_t)inuse;
968
34.7k
}
969
970
void
971
0
isc_mem_clearwater(isc_mem_t *mctx) {
972
0
  isc_mem_setwater(mctx, 0, 0);
973
0
}
974
975
void
976
0
isc_mem_setwater(isc_mem_t *ctx, size_t hiwater, size_t lowater) {
977
0
  REQUIRE(VALID_CONTEXT(ctx));
978
0
  REQUIRE(hiwater >= lowater);
979
980
0
  atomic_store_release(&ctx->hi_water, hiwater);
981
0
  atomic_store_release(&ctx->lo_water, lowater);
982
983
0
  return;
984
0
}
985
986
bool
987
0
isc_mem_isovermem(isc_mem_t *ctx) {
988
0
  REQUIRE(VALID_CONTEXT(ctx));
989
990
0
  size_t hiwater = atomic_load_relaxed(&ctx->hi_water);
991
0
  if (hiwater == 0) {
992
0
    return false;
993
0
  }
994
995
0
  size_t inuse = isc_mem_inuse(ctx);
996
0
  if (inuse >= hiwater) {
997
0
    return true;
998
0
  }
999
1000
0
  size_t lowater = atomic_load_relaxed(&ctx->lo_water);
1001
0
  if (inuse <= lowater) {
1002
0
    return false;
1003
0
  }
1004
1005
  /*
1006
   * Between lo_water and hi_water, return true with a probability
1007
   * that ramps linearly from 0 at lo_water to 1 at hi_water.  This
1008
   * spreads cache cleaning across many inserts instead of triggering
1009
   * a thundering herd once the hi_water mark is crossed.
1010
   */
1011
0
  uint32_t prob = (uint32_t)(((uint64_t)(inuse - lowater) * 256) /
1012
0
           (hiwater - lowater));
1013
0
  return isc_random8() < prob;
1014
0
}
1015
1016
const char *
1017
0
isc_mem_getname(isc_mem_t *ctx) {
1018
0
  REQUIRE(VALID_CONTEXT(ctx));
1019
1020
0
  if (ctx->name[0] == 0) {
1021
0
    return "";
1022
0
  }
1023
1024
0
  return ctx->name;
1025
0
}
1026
1027
/*
1028
 * Memory pool stuff
1029
 */
1030
1031
void
1032
isc__mempool_create(isc_mem_t *restrict mctx, const size_t element_size,
1033
45.8k
        const char *name, isc_mempool_t **restrict mpctxp FLARG) {
1034
45.8k
  isc_mempool_t *restrict mpctx = NULL;
1035
45.8k
  size_t size = element_size;
1036
1037
45.8k
  REQUIRE(VALID_CONTEXT(mctx));
1038
45.8k
  REQUIRE(size > 0U);
1039
45.8k
  REQUIRE(mpctxp != NULL && *mpctxp == NULL);
1040
45.8k
  REQUIRE(name != NULL);
1041
1042
  /*
1043
   * Mempools are stored as a linked list of element.
1044
   */
1045
45.8k
  if (size < sizeof(element)) {
1046
0
    size = sizeof(element);
1047
0
  }
1048
1049
  /*
1050
   * Allocate space for this pool, initialize values, and if all
1051
   * works well, attach to the memory context.
1052
   */
1053
45.8k
  mpctx = isc_mem_get(mctx, sizeof(isc_mempool_t));
1054
1055
45.8k
  *mpctx = (isc_mempool_t){
1056
45.8k
    .size = size,
1057
45.8k
    .freemax = 1,
1058
45.8k
    .fillcount = 1,
1059
45.8k
    .name = strdup(name),
1060
45.8k
  };
1061
1062
#if ISC_MEM_TRACKLINES
1063
  if ((mctx->debugging & ISC_MEM_DEBUGTRACE) != 0) {
1064
    fprintf(stderr,
1065
      "create pool %p func %s file %s line %u mctx %p\n",
1066
      mpctx, func, file, line, mctx);
1067
  }
1068
#endif /* ISC_MEM_TRACKLINES */
1069
1070
45.8k
  isc_mem_attach(mctx, &mpctx->mctx);
1071
45.8k
  mpctx->magic = MEMPOOL_MAGIC;
1072
1073
45.8k
  *mpctxp = (isc_mempool_t *)mpctx;
1074
1075
45.8k
  MCTXLOCK(mctx);
1076
45.8k
  ISC_LIST_INITANDAPPEND(mctx->pools, mpctx, link);
1077
45.8k
  mctx->poolcnt++;
1078
45.8k
  MCTXUNLOCK(mctx);
1079
45.8k
}
1080
1081
void
1082
45.8k
isc__mempool_destroy(isc_mempool_t **restrict mpctxp FLARG) {
1083
45.8k
  isc_mempool_t *restrict mpctx = NULL;
1084
45.8k
  isc_mem_t *mctx = NULL;
1085
45.8k
  element *restrict item = NULL;
1086
1087
45.8k
  REQUIRE(mpctxp != NULL);
1088
45.8k
  REQUIRE(VALID_MEMPOOL(*mpctxp));
1089
1090
45.8k
  mpctx = *mpctxp;
1091
45.8k
  *mpctxp = NULL;
1092
1093
45.8k
  mctx = mpctx->mctx;
1094
1095
#if ISC_MEM_TRACKLINES
1096
  if ((mctx->debugging & ISC_MEM_DEBUGTRACE) != 0) {
1097
    fprintf(stderr,
1098
      "destroy pool %p func %s file %s line %u mctx %p\n",
1099
      mpctx, func, file, line, mctx);
1100
  }
1101
#endif
1102
1103
45.8k
  if (mpctx->allocated > 0) {
1104
0
    UNEXPECTED_ERROR("mempool %s leaked memory", mpctx->name);
1105
0
  }
1106
45.8k
  REQUIRE(mpctx->allocated == 0);
1107
1108
  /*
1109
   * Return any items on the free list
1110
   */
1111
44.7M
  while (mpctx->items != NULL) {
1112
44.6M
    INSIST(mpctx->freecount > 0);
1113
44.6M
    mpctx->freecount--;
1114
1115
44.6M
    item = mpctx->items;
1116
44.6M
    mpctx->items = item->next;
1117
1118
44.6M
    mem_putstats(mctx, mpctx->size);
1119
44.6M
    mem_put(mctx, item, mpctx->size, 0);
1120
44.6M
  }
1121
1122
  /*
1123
   * Remove our linked list entry from the memory context.
1124
   */
1125
45.8k
  MCTXLOCK(mctx);
1126
45.8k
  ISC_LIST_UNLINK(mctx->pools, mpctx, link);
1127
45.8k
  mctx->poolcnt--;
1128
45.8k
  MCTXUNLOCK(mctx);
1129
1130
45.8k
  free(mpctx->name);
1131
1132
45.8k
  mpctx->magic = 0;
1133
1134
45.8k
  isc_mem_putanddetach(&mpctx->mctx, mpctx, sizeof(isc_mempool_t));
1135
45.8k
}
1136
1137
void *
1138
1.10M
isc__mempool_get(isc_mempool_t *restrict mpctx FLARG) {
1139
1.10M
  element *restrict item = NULL;
1140
1141
1.10M
  REQUIRE(VALID_MEMPOOL(mpctx));
1142
1143
1.10M
  mpctx->allocated++;
1144
1145
1.10M
  if (mpctx->items == NULL) {
1146
43.6k
    isc_mem_t *mctx = mpctx->mctx;
1147
43.6k
#if !__SANITIZE_ADDRESS__
1148
43.6k
    const size_t fillcount = mpctx->fillcount;
1149
#else
1150
    const size_t fillcount = 1;
1151
#endif
1152
    /*
1153
     * We need to dip into the well.  Fill up our free list.
1154
     */
1155
44.7M
    for (size_t i = 0; i < fillcount; i++) {
1156
44.7M
      item = mem_get(mctx, mpctx->size, 0);
1157
44.7M
      mem_getstats(mctx, mpctx->size);
1158
44.7M
      item->next = mpctx->items;
1159
44.7M
      mpctx->items = item;
1160
44.7M
      mpctx->freecount++;
1161
44.7M
    }
1162
43.6k
  }
1163
1164
1.10M
  INSIST(mpctx->items != NULL);
1165
1.10M
  item = mpctx->items;
1166
1167
1.10M
  mpctx->items = item->next;
1168
1169
1.10M
  INSIST(mpctx->freecount > 0);
1170
1.10M
  mpctx->freecount--;
1171
1.10M
  mpctx->gets++;
1172
1173
1.10M
  ADD_TRACE(mpctx->mctx, item, mpctx->size, func, file, line);
1174
1175
1.10M
  return item;
1176
1.10M
}
1177
1178
void
1179
1.10M
isc__mempool_put(isc_mempool_t *restrict mpctx, void *mem FLARG) {
1180
1.10M
  element *restrict item = NULL;
1181
1182
1.10M
  REQUIRE(VALID_MEMPOOL(mpctx));
1183
1.10M
  REQUIRE(mem != NULL);
1184
1185
1.10M
  isc_mem_t *mctx = mpctx->mctx;
1186
1.10M
  const size_t freecount = mpctx->freecount;
1187
1.10M
#if !__SANITIZE_ADDRESS__
1188
1.10M
  const size_t freemax = mpctx->freemax;
1189
#else
1190
  const size_t freemax = 0;
1191
#endif
1192
1193
1.10M
  INSIST(mpctx->allocated > 0);
1194
1.10M
  mpctx->allocated--;
1195
1196
1.10M
  DELETE_TRACE(mctx, mem, mpctx->size, func, file, line);
1197
1198
  /*
1199
   * If our free list is full, return this to the mctx directly.
1200
   */
1201
1.10M
  if (freecount >= freemax) {
1202
20.4k
    mem_putstats(mctx, mpctx->size);
1203
20.4k
    mem_put(mctx, mem, mpctx->size, 0);
1204
20.4k
    return;
1205
20.4k
  }
1206
1207
  /*
1208
   * Otherwise, attach it to our free list and bump the counter.
1209
   */
1210
1.08M
  item = (element *)mem;
1211
1.08M
  item->next = mpctx->items;
1212
1.08M
  mpctx->items = item;
1213
1.08M
  mpctx->freecount++;
1214
1.08M
}
1215
1216
/*
1217
 * Quotas
1218
 */
1219
1220
void
1221
isc_mempool_setfreemax(isc_mempool_t *restrict mpctx,
1222
45.8k
           const unsigned int limit) {
1223
45.8k
  REQUIRE(VALID_MEMPOOL(mpctx));
1224
45.8k
  mpctx->freemax = limit;
1225
45.8k
}
1226
1227
unsigned int
1228
0
isc_mempool_getfreemax(isc_mempool_t *restrict mpctx) {
1229
0
  REQUIRE(VALID_MEMPOOL(mpctx));
1230
1231
0
  return mpctx->freemax;
1232
0
}
1233
1234
unsigned int
1235
0
isc_mempool_getfreecount(isc_mempool_t *restrict mpctx) {
1236
0
  REQUIRE(VALID_MEMPOOL(mpctx));
1237
1238
0
  return mpctx->freecount;
1239
0
}
1240
1241
unsigned int
1242
45.8k
isc_mempool_getallocated(isc_mempool_t *restrict mpctx) {
1243
45.8k
  REQUIRE(VALID_MEMPOOL(mpctx));
1244
1245
45.8k
  return mpctx->allocated;
1246
45.8k
}
1247
1248
void
1249
isc_mempool_setfillcount(isc_mempool_t *restrict mpctx,
1250
45.8k
       unsigned int const limit) {
1251
45.8k
  REQUIRE(VALID_MEMPOOL(mpctx));
1252
45.8k
  REQUIRE(limit > 0);
1253
1254
45.8k
  mpctx->fillcount = limit;
1255
45.8k
}
1256
1257
unsigned int
1258
0
isc_mempool_getfillcount(isc_mempool_t *restrict mpctx) {
1259
0
  REQUIRE(VALID_MEMPOOL(mpctx));
1260
1261
0
  return mpctx->fillcount;
1262
0
}
1263
1264
/*
1265
 * Requires contextslock to be held by caller.
1266
 */
1267
#if ISC_MEM_TRACKLINES
1268
static void
1269
print_contexts(FILE *file) {
1270
  ISC_LIST_FOREACH(contexts, ctx, link) {
1271
    fprintf(file, "context: %p (%s): %" PRIuFAST32 " references\n",
1272
      ctx, ctx->name[0] == 0 ? "<unknown>" : ctx->name,
1273
      isc_refcount_current(&ctx->references));
1274
    print_active(ctx, file);
1275
  }
1276
  fflush(file);
1277
}
1278
#endif
1279
1280
static atomic_uintptr_t checkdestroyed = 0;
1281
1282
void
1283
998
isc_mem_checkdestroyed(FILE *file) {
1284
998
  atomic_store_release(&checkdestroyed, (uintptr_t)file);
1285
998
}
1286
1287
void
1288
0
isc__mem_checkdestroyed(void) {
1289
0
  FILE *file = (FILE *)atomic_load_acquire(&checkdestroyed);
1290
1291
0
  if (file == NULL) {
1292
0
    return;
1293
0
  }
1294
1295
0
  LOCK(&contextslock);
1296
0
  if (!ISC_LIST_EMPTY(contexts)) {
1297
#if ISC_MEM_TRACKLINES
1298
    if ((mem_debugging & TRACE_OR_RECORD) != 0) {
1299
      print_contexts(file);
1300
    }
1301
#endif /* if ISC_MEM_TRACKLINES */
1302
0
    UNREACHABLE();
1303
0
  }
1304
0
  UNLOCK(&contextslock);
1305
0
}
1306
1307
unsigned int
1308
0
isc_mem_references(isc_mem_t *ctx) {
1309
0
  return isc_refcount_current(&ctx->references);
1310
0
}
1311
1312
#ifdef HAVE_LIBXML2
1313
#define TRY0(a)                     \
1314
  do {                        \
1315
    xmlrc = (a);        \
1316
    if (xmlrc < 0)      \
1317
      goto error; \
1318
  } while (0)
1319
static int
1320
xml_renderctx(isc_mem_t *ctx, size_t *inuse, xmlTextWriterPtr writer) {
1321
  REQUIRE(VALID_CONTEXT(ctx));
1322
1323
  int xmlrc;
1324
1325
  MCTXLOCK(ctx);
1326
1327
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "context"));
1328
1329
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "id"));
1330
  TRY0(xmlTextWriterWriteFormatString(writer, "%p", ctx));
1331
  TRY0(xmlTextWriterEndElement(writer)); /* id */
1332
1333
  if (ctx->name[0] != 0) {
1334
    TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "name"));
1335
    TRY0(xmlTextWriterWriteFormatString(writer, "%s", ctx->name));
1336
    TRY0(xmlTextWriterEndElement(writer)); /* name */
1337
  }
1338
1339
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "references"));
1340
  TRY0(xmlTextWriterWriteFormatString(
1341
    writer, "%" PRIuFAST32,
1342
    isc_refcount_current(&ctx->references)));
1343
  TRY0(xmlTextWriterEndElement(writer)); /* references */
1344
1345
  *inuse += isc_mem_inuse(ctx);
1346
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "inuse"));
1347
  TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
1348
              (uint64_t)isc_mem_inuse(ctx)));
1349
  TRY0(xmlTextWriterEndElement(writer)); /* inuse */
1350
1351
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "malloced"));
1352
  TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
1353
              (uint64_t)isc_mem_inuse(ctx)));
1354
  TRY0(xmlTextWriterEndElement(writer)); /* malloced */
1355
1356
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "pools"));
1357
  TRY0(xmlTextWriterWriteFormatString(writer, "%u", ctx->poolcnt));
1358
  TRY0(xmlTextWriterEndElement(writer)); /* pools */
1359
1360
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "hiwater"));
1361
  TRY0(xmlTextWriterWriteFormatString(
1362
    writer, "%" PRIu64 "",
1363
    (uint64_t)atomic_load_relaxed(&ctx->hi_water)));
1364
  TRY0(xmlTextWriterEndElement(writer)); /* hiwater */
1365
1366
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "lowater"));
1367
  TRY0(xmlTextWriterWriteFormatString(
1368
    writer, "%" PRIu64 "",
1369
    (uint64_t)atomic_load_relaxed(&ctx->lo_water)));
1370
  TRY0(xmlTextWriterEndElement(writer)); /* lowater */
1371
1372
  TRY0(xmlTextWriterEndElement(writer)); /* context */
1373
1374
error:
1375
  MCTXUNLOCK(ctx);
1376
1377
  return xmlrc;
1378
}
1379
1380
int
1381
isc_mem_renderxml(void *writer0) {
1382
  size_t inuse = 0;
1383
  int xmlrc;
1384
  xmlTextWriterPtr writer = (xmlTextWriterPtr)writer0;
1385
1386
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "contexts"));
1387
1388
  LOCK(&contextslock);
1389
  ISC_LIST_FOREACH(contexts, ctx, link) {
1390
    xmlrc = xml_renderctx(ctx, &inuse, writer);
1391
    if (xmlrc < 0) {
1392
      UNLOCK(&contextslock);
1393
      goto error;
1394
    }
1395
  }
1396
  UNLOCK(&contextslock);
1397
1398
  TRY0(xmlTextWriterEndElement(writer)); /* contexts */
1399
1400
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "summary"));
1401
1402
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "Malloced"));
1403
  TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
1404
              (uint64_t)inuse));
1405
  TRY0(xmlTextWriterEndElement(writer)); /* malloced */
1406
1407
  TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "InUse"));
1408
  TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
1409
              (uint64_t)inuse));
1410
  TRY0(xmlTextWriterEndElement(writer)); /* InUse */
1411
1412
  TRY0(xmlTextWriterEndElement(writer)); /* summary */
1413
error:
1414
  return xmlrc;
1415
}
1416
1417
#endif /* HAVE_LIBXML2 */
1418
1419
#ifdef HAVE_JSON_C
1420
#define CHECKMEM(m) RUNTIME_CHECK(m != NULL)
1421
1422
static isc_result_t
1423
json_renderctx(isc_mem_t *ctx, size_t *inuse, json_object *array) {
1424
  REQUIRE(VALID_CONTEXT(ctx));
1425
  REQUIRE(array != NULL);
1426
1427
  json_object *ctxobj, *obj;
1428
  char buf[1024];
1429
1430
  MCTXLOCK(ctx);
1431
1432
  *inuse += isc_mem_inuse(ctx);
1433
1434
  ctxobj = json_object_new_object();
1435
  CHECKMEM(ctxobj);
1436
1437
  snprintf(buf, sizeof(buf), "%p", ctx);
1438
  obj = json_object_new_string(buf);
1439
  CHECKMEM(obj);
1440
  json_object_object_add(ctxobj, "id", obj);
1441
1442
  if (ctx->name[0] != 0) {
1443
    obj = json_object_new_string(ctx->name);
1444
    CHECKMEM(obj);
1445
    json_object_object_add(ctxobj, "name", obj);
1446
  }
1447
1448
  obj = json_object_new_int64(isc_refcount_current(&ctx->references));
1449
  CHECKMEM(obj);
1450
  json_object_object_add(ctxobj, "references", obj);
1451
1452
  obj = json_object_new_int64(isc_mem_inuse(ctx));
1453
  CHECKMEM(obj);
1454
  json_object_object_add(ctxobj, "malloced", obj);
1455
1456
  obj = json_object_new_int64(isc_mem_inuse(ctx));
1457
  CHECKMEM(obj);
1458
  json_object_object_add(ctxobj, "inuse", obj);
1459
1460
  obj = json_object_new_int64(ctx->poolcnt);
1461
  CHECKMEM(obj);
1462
  json_object_object_add(ctxobj, "pools", obj);
1463
1464
  obj = json_object_new_int64(atomic_load_relaxed(&ctx->hi_water));
1465
  CHECKMEM(obj);
1466
  json_object_object_add(ctxobj, "hiwater", obj);
1467
1468
  obj = json_object_new_int64(atomic_load_relaxed(&ctx->lo_water));
1469
  CHECKMEM(obj);
1470
  json_object_object_add(ctxobj, "lowater", obj);
1471
1472
  MCTXUNLOCK(ctx);
1473
  json_object_array_add(array, ctxobj);
1474
  return ISC_R_SUCCESS;
1475
}
1476
1477
isc_result_t
1478
isc_mem_renderjson(void *memobj0) {
1479
  isc_result_t result = ISC_R_SUCCESS;
1480
  size_t inuse = 0;
1481
  json_object *ctxarray, *obj;
1482
  json_object *memobj = (json_object *)memobj0;
1483
1484
  ctxarray = json_object_new_array();
1485
  CHECKMEM(ctxarray);
1486
1487
  LOCK(&contextslock);
1488
  ISC_LIST_FOREACH(contexts, ctx, link) {
1489
    result = json_renderctx(ctx, &inuse, ctxarray);
1490
    if (result != ISC_R_SUCCESS) {
1491
      UNLOCK(&contextslock);
1492
      goto error;
1493
    }
1494
  }
1495
  UNLOCK(&contextslock);
1496
1497
  obj = json_object_new_int64(inuse);
1498
  CHECKMEM(obj);
1499
  json_object_object_add(memobj, "InUse", obj);
1500
1501
  obj = json_object_new_int64(inuse);
1502
  CHECKMEM(obj);
1503
  json_object_object_add(memobj, "Malloced", obj);
1504
1505
  json_object_object_add(memobj, "contexts", ctxarray);
1506
  return ISC_R_SUCCESS;
1507
1508
error:
1509
  if (ctxarray != NULL) {
1510
    json_object_put(ctxarray);
1511
  }
1512
  return result;
1513
}
1514
#endif /* HAVE_JSON_C */
1515
1516
void
1517
34.8k
isc__mem_create(const char *name, isc_mem_t **mctxp FLARG) {
1518
34.8k
  mem_create(name, mctxp, mem_debugging, 0);
1519
#if ISC_MEM_TRACKLINES
1520
  if ((mem_debugging & ISC_MEM_DEBUGTRACE) != 0) {
1521
    fprintf(stderr, "create mctx %p func %s file %s line %u\n",
1522
      *mctxp, func, file, line);
1523
  }
1524
#endif /* ISC_MEM_TRACKLINES */
1525
34.8k
}
1526
1527
void
1528
0
isc__mem_printactive(isc_mem_t *ctx, FILE *file) {
1529
#if ISC_MEM_TRACKLINES
1530
  REQUIRE(VALID_CONTEXT(ctx));
1531
  REQUIRE(file != NULL);
1532
1533
  print_active(ctx, file);
1534
#else  /* if ISC_MEM_TRACKLINES */
1535
0
  UNUSED(ctx);
1536
0
  UNUSED(file);
1537
0
#endif /* if ISC_MEM_TRACKLINES */
1538
0
}