mem.c revision 1.10 1 /* $NetBSD: mem.c,v 1.10 2021/04/29 17:26:12 christos Exp $ */
2
3 /*
4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
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 <errno.h>
17 #include <inttypes.h>
18 #include <limits.h>
19 #include <stdbool.h>
20 #include <stddef.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23
24 #include <isc/bind9.h>
25 #include <isc/hash.h>
26 #include <isc/lib.h>
27 #include <isc/magic.h>
28 #include <isc/mem.h>
29 #include <isc/mutex.h>
30 #include <isc/once.h>
31 #include <isc/print.h>
32 #include <isc/refcount.h>
33 #include <isc/strerr.h>
34 #include <isc/string.h>
35 #include <isc/util.h>
36
37 #ifdef HAVE_LIBXML2
38 #include <libxml/xmlwriter.h>
39 #define ISC_XMLCHAR (const xmlChar *)
40 #endif /* HAVE_LIBXML2 */
41
42 #ifdef HAVE_JSON_C
43 #include <json_object.h>
44 #endif /* HAVE_JSON_C */
45
46 #include "mem_p.h"
47
48 #define MCTXLOCK(m) LOCK(&m->lock)
49 #define MCTXUNLOCK(m) UNLOCK(&m->lock)
50
51 #ifndef ISC_MEM_DEBUGGING
52 #define ISC_MEM_DEBUGGING 0
53 #endif /* ifndef ISC_MEM_DEBUGGING */
54 LIBISC_EXTERNAL_DATA unsigned int isc_mem_debugging = ISC_MEM_DEBUGGING;
55 LIBISC_EXTERNAL_DATA unsigned int isc_mem_defaultflags = ISC_MEMFLAG_DEFAULT;
56
57 /*
58 * Constants.
59 */
60
61 #define DEF_MAX_SIZE 1100
62 #define DEF_MEM_TARGET 4096
63 #define ALIGNMENT_SIZE 8U /*%< must be a power of 2 */
64 #define NUM_BASIC_BLOCKS 64 /*%< must be > 1 */
65 #define TABLE_INCREMENT 1024
66 #define DEBUG_TABLE_COUNT 512U
67
68 /*
69 * Types.
70 */
71 typedef struct isc__mem isc__mem_t;
72 typedef struct isc__mempool isc__mempool_t;
73
74 #if ISC_MEM_TRACKLINES
75 typedef struct debuglink debuglink_t;
76 struct debuglink {
77 ISC_LINK(debuglink_t) link;
78 const void *ptr;
79 size_t size;
80 const char *file;
81 unsigned int line;
82 };
83
84 typedef ISC_LIST(debuglink_t) debuglist_t;
85
86 #define FLARG_PASS , file, line
87 #define FLARG , const char *file, unsigned int line
88 #else /* if ISC_MEM_TRACKLINES */
89 #define FLARG_PASS
90 #define FLARG
91 #endif /* if ISC_MEM_TRACKLINES */
92
93 typedef struct element element;
94 struct element {
95 element *next;
96 };
97
98 typedef struct {
99 /*!
100 * This structure must be ALIGNMENT_SIZE bytes.
101 */
102 union {
103 size_t size;
104 isc__mem_t *ctx;
105 char bytes[ALIGNMENT_SIZE];
106 } u;
107 } size_info;
108
109 struct stats {
110 unsigned long gets;
111 unsigned long totalgets;
112 unsigned long blocks;
113 unsigned long freefrags;
114 };
115
116 #define MEM_MAGIC ISC_MAGIC('M', 'e', 'm', 'C')
117 #define VALID_CONTEXT(c) ISC_MAGIC_VALID(c, MEM_MAGIC)
118
119 /* List of all active memory contexts. */
120
121 static ISC_LIST(isc__mem_t) contexts;
122
123 static isc_once_t init_once = ISC_ONCE_INIT;
124 static isc_once_t shut_once = ISC_ONCE_INIT;
125 static isc_mutex_t contextslock;
126
127 /*%
128 * Total size of lost memory due to a bug of external library.
129 * Locked by the global lock.
130 */
131 static uint64_t totallost;
132
133 /*%
134 * Memory allocation and free function definitions.
135 * isc__memalloc_t must deal with memory allocation failure
136 * and must never return NULL.
137 */
138 typedef void *(*isc__memalloc_t)(size_t);
139 typedef void (*isc__memfree_t)(void *);
140
141 struct isc__mem {
142 isc_mem_t common;
143 unsigned int flags;
144 isc_mutex_t lock;
145 isc__memalloc_t memalloc;
146 isc__memfree_t memfree;
147 size_t max_size;
148 bool checkfree;
149 struct stats *stats;
150 isc_refcount_t references;
151 char name[16];
152 void *tag;
153 size_t total;
154 size_t inuse;
155 size_t maxinuse;
156 size_t malloced;
157 size_t maxmalloced;
158 size_t hi_water;
159 size_t lo_water;
160 bool hi_called;
161 bool is_overmem;
162 isc_mem_water_t water;
163 void *water_arg;
164 ISC_LIST(isc__mempool_t) pools;
165 unsigned int poolcnt;
166
167 /* ISC_MEMFLAG_INTERNAL */
168 size_t mem_target;
169 element **freelists;
170 element *basic_blocks;
171 unsigned char **basic_table;
172 unsigned int basic_table_count;
173 unsigned int basic_table_size;
174 unsigned char *lowest;
175 unsigned char *highest;
176
177 #if ISC_MEM_TRACKLINES
178 debuglist_t *debuglist;
179 size_t debuglistcnt;
180 #endif /* if ISC_MEM_TRACKLINES */
181
182 ISC_LINK(isc__mem_t) link;
183 };
184
185 #define MEMPOOL_MAGIC ISC_MAGIC('M', 'E', 'M', 'p')
186 #define VALID_MEMPOOL(c) ISC_MAGIC_VALID(c, MEMPOOL_MAGIC)
187
188 struct isc__mempool {
189 /* always unlocked */
190 isc_mempool_t common; /*%< common header of mempool's */
191 isc_mutex_t *lock; /*%< optional lock */
192 isc__mem_t *mctx; /*%< our memory context */
193 /*%< locked via the memory context's lock */
194 ISC_LINK(isc__mempool_t) link; /*%< next pool in this mem context */
195 /*%< optionally locked from here down */
196 element *items; /*%< low water item list */
197 size_t size; /*%< size of each item on this pool */
198 unsigned int maxalloc; /*%< max number of items allowed */
199 unsigned int allocated; /*%< # of items currently given out */
200 unsigned int freecount; /*%< # of items on reserved list */
201 unsigned int freemax; /*%< # of items allowed on free list */
202 unsigned int fillcount; /*%< # of items to fetch on each fill */
203 /*%< Stats only. */
204 unsigned int gets; /*%< # of requests to this pool */
205 /*%< Debugging only. */
206 #if ISC_MEMPOOL_NAMES
207 char name[16]; /*%< printed name in stats reports */
208 #endif /* if ISC_MEMPOOL_NAMES */
209 };
210
211 /*
212 * Private Inline-able.
213 */
214
215 #if !ISC_MEM_TRACKLINES
216 #define ADD_TRACE(a, b, c, d, e)
217 #define DELETE_TRACE(a, b, c, d, e)
218 #define ISC_MEMFUNC_SCOPE
219 #else /* if !ISC_MEM_TRACKLINES */
220 #define TRACE_OR_RECORD (ISC_MEM_DEBUGTRACE | ISC_MEM_DEBUGRECORD)
221 #define ADD_TRACE(a, b, c, d, e) \
222 do { \
223 if (ISC_UNLIKELY((isc_mem_debugging & TRACE_OR_RECORD) != 0 && \
224 b != NULL)) \
225 add_trace_entry(a, b, c, d, e); \
226 } while (0)
227 #define DELETE_TRACE(a, b, c, d, e) \
228 do { \
229 if (ISC_UNLIKELY((isc_mem_debugging & TRACE_OR_RECORD) != 0 && \
230 b != NULL)) \
231 delete_trace_entry(a, b, c, d, e); \
232 } while (0)
233
234 static void
235 print_active(isc__mem_t *ctx, FILE *out);
236
237 #endif /* ISC_MEM_TRACKLINES */
238
239 static void *
240 isc___mem_get(isc_mem_t *ctx, size_t size FLARG);
241 static void
242 isc___mem_put(isc_mem_t *ctx, void *ptr, size_t size FLARG);
243 static void
244 isc___mem_putanddetach(isc_mem_t **ctxp, void *ptr, size_t size FLARG);
245 static void *
246 isc___mem_allocate(isc_mem_t *ctx, size_t size FLARG);
247 static void *
248 isc___mem_reallocate(isc_mem_t *ctx, void *ptr, size_t size FLARG);
249 static char *
250 isc___mem_strdup(isc_mem_t *mctx, const char *s FLARG);
251 static void
252 isc___mem_free(isc_mem_t *ctx, void *ptr FLARG);
253
254 static isc_memmethods_t memmethods = {
255 isc___mem_get, isc___mem_put, isc___mem_putanddetach,
256 isc___mem_allocate, isc___mem_reallocate, isc___mem_strdup,
257 isc___mem_free,
258 };
259
260 #if ISC_MEM_TRACKLINES
261 /*!
262 * mctx must be locked.
263 */
264 static void
265 add_trace_entry(isc__mem_t *mctx, const void *ptr, size_t size FLARG) {
266 debuglink_t *dl;
267 uint32_t hash;
268 uint32_t idx;
269
270 if ((isc_mem_debugging & ISC_MEM_DEBUGTRACE) != 0) {
271 fprintf(stderr, "add %p size %zu file %s line %u mctx %p\n",
272 ptr, size, file, line, mctx);
273 }
274
275 if (mctx->debuglist == NULL) {
276 return;
277 }
278
279 #ifdef __COVERITY__
280 /*
281 * Use simple conversion from pointer to hash to avoid
282 * tainting 'ptr' due to byte swap in isc_hash_function.
283 */
284 hash = (uintptr_t)ptr >> 3;
285 #else
286 hash = isc_hash_function(&ptr, sizeof(ptr), true);
287 #endif
288 idx = hash % DEBUG_TABLE_COUNT;
289
290 dl = malloc(sizeof(debuglink_t));
291 INSIST(dl != NULL);
292 mctx->malloced += sizeof(debuglink_t);
293 if (mctx->malloced > mctx->maxmalloced) {
294 mctx->maxmalloced = mctx->malloced;
295 }
296
297 ISC_LINK_INIT(dl, link);
298 dl->ptr = ptr;
299 dl->size = size;
300 dl->file = file;
301 dl->line = line;
302
303 ISC_LIST_PREPEND(mctx->debuglist[idx], dl, link);
304 mctx->debuglistcnt++;
305 }
306
307 static void
308 delete_trace_entry(isc__mem_t *mctx, const void *ptr, size_t size,
309 const char *file, unsigned int line) {
310 debuglink_t *dl;
311 uint32_t hash;
312 uint32_t idx;
313
314 if ((isc_mem_debugging & ISC_MEM_DEBUGTRACE) != 0) {
315 fprintf(stderr, "del %p size %zu file %s line %u mctx %p\n",
316 ptr, size, file, line, mctx);
317 }
318
319 if (mctx->debuglist == NULL) {
320 return;
321 }
322
323 #ifdef __COVERITY__
324 /*
325 * Use simple conversion from pointer to hash to avoid
326 * tainting 'ptr' due to byte swap in isc_hash_function.
327 */
328 hash = (uintptr_t)ptr >> 3;
329 #else
330 hash = isc_hash_function(&ptr, sizeof(ptr), true);
331 #endif
332 idx = hash % DEBUG_TABLE_COUNT;
333
334 dl = ISC_LIST_HEAD(mctx->debuglist[idx]);
335 while (ISC_LIKELY(dl != NULL)) {
336 if (ISC_UNLIKELY(dl->ptr == ptr)) {
337 ISC_LIST_UNLINK(mctx->debuglist[idx], dl, link);
338 mctx->malloced -= sizeof(*dl);
339 free(dl);
340 return;
341 }
342 dl = ISC_LIST_NEXT(dl, link);
343 }
344
345 /*
346 * If we get here, we didn't find the item on the list. We're
347 * screwed.
348 */
349 INSIST(0);
350 ISC_UNREACHABLE();
351 }
352 #endif /* ISC_MEM_TRACKLINES */
353
354 static inline size_t
355 rmsize(size_t size) {
356 /*
357 * round down to ALIGNMENT_SIZE
358 */
359 return (size & (~(ALIGNMENT_SIZE - 1)));
360 }
361
362 static inline size_t
363 quantize(size_t size) {
364 /*!
365 * Round up the result in order to get a size big
366 * enough to satisfy the request and be aligned on ALIGNMENT_SIZE
367 * byte boundaries.
368 */
369
370 if (size == 0U) {
371 return (ALIGNMENT_SIZE);
372 }
373 return ((size + ALIGNMENT_SIZE - 1) & (~(ALIGNMENT_SIZE - 1)));
374 }
375
376 static inline void
377 more_basic_blocks(isc__mem_t *ctx) {
378 void *tmp;
379 unsigned char *curr, *next;
380 unsigned char *first, *last;
381 unsigned char **table;
382 unsigned int table_size;
383
384 /* Require: we hold the context lock. */
385
386 INSIST(ctx->basic_table_count <= ctx->basic_table_size);
387 if (ctx->basic_table_count == ctx->basic_table_size) {
388 table_size = ctx->basic_table_size + TABLE_INCREMENT;
389 table = (ctx->memalloc)(table_size * sizeof(unsigned char *));
390 ctx->malloced += table_size * sizeof(unsigned char *);
391 if (ctx->malloced > ctx->maxmalloced) {
392 ctx->maxmalloced = ctx->malloced;
393 }
394 if (ctx->basic_table_size != 0) {
395 memmove(table, ctx->basic_table,
396 ctx->basic_table_size *
397 sizeof(unsigned char *));
398 (ctx->memfree)(ctx->basic_table);
399 ctx->malloced -= ctx->basic_table_size *
400 sizeof(unsigned char *);
401 }
402 ctx->basic_table = table;
403 ctx->basic_table_size = table_size;
404 }
405
406 tmp = (ctx->memalloc)(NUM_BASIC_BLOCKS * ctx->mem_target);
407 ctx->total += NUM_BASIC_BLOCKS * ctx->mem_target;
408 ctx->basic_table[ctx->basic_table_count] = tmp;
409 ctx->basic_table_count++;
410 ctx->malloced += NUM_BASIC_BLOCKS * ctx->mem_target;
411 if (ctx->malloced > ctx->maxmalloced) {
412 ctx->maxmalloced = ctx->malloced;
413 }
414
415 curr = tmp;
416 next = curr + ctx->mem_target;
417 for (int i = 0; i < (NUM_BASIC_BLOCKS - 1); i++) {
418 ((element *)curr)->next = (element *)next;
419 curr = next;
420 next += ctx->mem_target;
421 }
422 /*
423 * curr is now pointing at the last block in the
424 * array.
425 */
426 ((element *)curr)->next = NULL;
427 first = tmp;
428 last = first + NUM_BASIC_BLOCKS * ctx->mem_target - 1;
429 if (first < ctx->lowest || ctx->lowest == NULL) {
430 ctx->lowest = first;
431 }
432 if (last > ctx->highest) {
433 ctx->highest = last;
434 }
435 ctx->basic_blocks = tmp;
436 }
437
438 static inline void
439 more_frags(isc__mem_t *ctx, size_t new_size) {
440 int frags;
441 size_t total_size;
442 void *tmp;
443 unsigned char *curr, *next;
444
445 /*!
446 * Try to get more fragments by chopping up a basic block.
447 */
448
449 if (ctx->basic_blocks == NULL) {
450 more_basic_blocks(ctx);
451 }
452 INSIST(ctx->basic_blocks != NULL);
453
454 total_size = ctx->mem_target;
455 tmp = ctx->basic_blocks;
456 ctx->basic_blocks = ctx->basic_blocks->next;
457 frags = (int)(total_size / new_size);
458 ctx->stats[new_size].blocks++;
459 ctx->stats[new_size].freefrags += frags;
460 /*
461 * Set up a linked-list of blocks of size
462 * "new_size".
463 */
464 curr = tmp;
465 next = curr + new_size;
466 total_size -= new_size;
467 for (int i = 0; i < (frags - 1); i++) {
468 ((element *)curr)->next = (element *)next;
469 curr = next;
470 next += new_size;
471 total_size -= new_size;
472 }
473 /*
474 * Add the remaining fragment of the basic block to a free list.
475 */
476 total_size = rmsize(total_size);
477 if (total_size > 0U) {
478 ((element *)next)->next = ctx->freelists[total_size];
479 ctx->freelists[total_size] = (element *)next;
480 ctx->stats[total_size].freefrags++;
481 }
482 /*
483 * curr is now pointing at the last block in the
484 * array.
485 */
486 ((element *)curr)->next = NULL;
487 ctx->freelists[new_size] = tmp;
488 }
489
490 static inline void *
491 mem_getunlocked(isc__mem_t *ctx, size_t size) {
492 size_t new_size = quantize(size);
493 void *ret;
494
495 if (new_size >= ctx->max_size) {
496 /*
497 * memget() was called on something beyond our upper limit.
498 */
499 ret = (ctx->memalloc)(size);
500 ctx->total += size;
501 ctx->inuse += size;
502 ctx->stats[ctx->max_size].gets++;
503 ctx->stats[ctx->max_size].totalgets++;
504 ctx->malloced += size;
505 if (ctx->malloced > ctx->maxmalloced) {
506 ctx->maxmalloced = ctx->malloced;
507 }
508 /*
509 * If we don't set new_size to size, then the
510 * ISC_MEMFLAG_FILL code might write over bytes we don't
511 * own.
512 */
513 new_size = size;
514 goto done;
515 }
516 /*
517 * If there are no blocks in the free list for this size, get a chunk
518 * of memory and then break it up into "new_size"-sized blocks, adding
519 * them to the free list.
520 */
521 if (ctx->freelists[new_size] == NULL) {
522 more_frags(ctx, new_size);
523 }
524 INSIST(ctx->freelists[new_size] != NULL);
525
526 /*
527 * The free list uses the "rounded-up" size "new_size".
528 */
529
530 ret = ctx->freelists[new_size];
531 ctx->freelists[new_size] = ctx->freelists[new_size]->next;
532
533 /*
534 * The stats[] uses the _actual_ "size" requested by the
535 * caller, with the caveat (in the code above) that "size" >= the
536 * max. size (max_size) ends up getting recorded as a call to
537 * max_size.
538 */
539 ctx->stats[size].gets++;
540 ctx->stats[size].totalgets++;
541 ctx->stats[new_size].freefrags--;
542 ctx->inuse += new_size;
543
544 done:
545 if (ISC_UNLIKELY((ctx->flags & ISC_MEMFLAG_FILL) != 0) &&
546 ISC_LIKELY(ret != NULL))
547 {
548 memset(ret, 0xbe, new_size); /* Mnemonic for "beef". */
549 }
550
551 return (ret);
552 }
553
554 #if ISC_MEM_CHECKOVERRUN
555 static inline void
556 check_overrun(void *mem, size_t size, size_t new_size) {
557 unsigned char *cp;
558
559 cp = (unsigned char *)mem;
560 cp += size;
561 while (size < new_size) {
562 INSIST(*cp == 0xbe);
563 cp++;
564 size++;
565 }
566 }
567 #endif /* if ISC_MEM_CHECKOVERRUN */
568
569 /* coverity[+free : arg-1] */
570 static inline void
571 mem_putunlocked(isc__mem_t *ctx, void *mem, size_t size) {
572 size_t new_size = quantize(size);
573
574 if (new_size >= ctx->max_size) {
575 /*
576 * memput() called on something beyond our upper limit.
577 */
578 if (ISC_UNLIKELY((ctx->flags & ISC_MEMFLAG_FILL) != 0)) {
579 memset(mem, 0xde, size); /* Mnemonic for "dead". */
580 }
581
582 (ctx->memfree)(mem);
583 INSIST(ctx->stats[ctx->max_size].gets != 0U);
584 ctx->stats[ctx->max_size].gets--;
585 INSIST(size <= ctx->inuse);
586 ctx->inuse -= size;
587 ctx->malloced -= size;
588 return;
589 }
590
591 if (ISC_UNLIKELY((ctx->flags & ISC_MEMFLAG_FILL) != 0)) {
592 #if ISC_MEM_CHECKOVERRUN
593 check_overrun(mem, size, new_size);
594 #endif /* if ISC_MEM_CHECKOVERRUN */
595 memset(mem, 0xde, new_size); /* Mnemonic for "dead". */
596 }
597
598 /*
599 * The free list uses the "rounded-up" size "new_size".
600 */
601 ((element *)mem)->next = ctx->freelists[new_size];
602 ctx->freelists[new_size] = (element *)mem;
603
604 /*
605 * The stats[] uses the _actual_ "size" requested by the
606 * caller, with the caveat (in the code above) that "size" >= the
607 * max. size (max_size) ends up getting recorded as a call to
608 * max_size.
609 */
610 INSIST(ctx->stats[size].gets != 0U);
611 ctx->stats[size].gets--;
612 ctx->stats[new_size].freefrags++;
613 ctx->inuse -= new_size;
614 }
615
616 /*!
617 * Perform a malloc, doing memory filling and overrun detection as necessary.
618 */
619 static inline void *
620 mem_get(isc__mem_t *ctx, size_t size) {
621 char *ret;
622
623 #if ISC_MEM_CHECKOVERRUN
624 size += 1;
625 #endif /* if ISC_MEM_CHECKOVERRUN */
626 ret = (ctx->memalloc)(size);
627
628 if (ISC_UNLIKELY((ctx->flags & ISC_MEMFLAG_FILL) != 0)) {
629 if (ISC_LIKELY(ret != NULL)) {
630 memset(ret, 0xbe, size); /* Mnemonic for "beef". */
631 }
632 }
633 #if ISC_MEM_CHECKOVERRUN
634 else
635 {
636 if (ISC_LIKELY(ret != NULL)) {
637 ret[size - 1] = 0xbe;
638 }
639 }
640 #endif /* if ISC_MEM_CHECKOVERRUN */
641
642 return (ret);
643 }
644
645 /*!
646 * Perform a free, doing memory filling and overrun detection as necessary.
647 */
648 /* coverity[+free : arg-1] */
649 static inline void
650 mem_put(isc__mem_t *ctx, void *mem, size_t size) {
651 #if ISC_MEM_CHECKOVERRUN
652 INSIST(((unsigned char *)mem)[size] == 0xbe);
653 size += 1;
654 #endif /* if ISC_MEM_CHECKOVERRUN */
655 if (ISC_UNLIKELY((ctx->flags & ISC_MEMFLAG_FILL) != 0)) {
656 memset(mem, 0xde, size); /* Mnemonic for "dead". */
657 }
658 (ctx->memfree)(mem);
659 }
660
661 /*!
662 * Update internal counters after a memory get.
663 */
664 static inline void
665 mem_getstats(isc__mem_t *ctx, size_t size) {
666 ctx->total += size;
667 ctx->inuse += size;
668
669 if (size > ctx->max_size) {
670 ctx->stats[ctx->max_size].gets++;
671 ctx->stats[ctx->max_size].totalgets++;
672 } else {
673 ctx->stats[size].gets++;
674 ctx->stats[size].totalgets++;
675 }
676
677 #if ISC_MEM_CHECKOVERRUN
678 size += 1;
679 #endif /* if ISC_MEM_CHECKOVERRUN */
680 ctx->malloced += size;
681 if (ctx->malloced > ctx->maxmalloced) {
682 ctx->maxmalloced = ctx->malloced;
683 }
684 }
685
686 /*!
687 * Update internal counters after a memory put.
688 */
689 static inline void
690 mem_putstats(isc__mem_t *ctx, void *ptr, size_t size) {
691 UNUSED(ptr);
692
693 INSIST(ctx->inuse >= size);
694 ctx->inuse -= size;
695
696 if (size > ctx->max_size) {
697 INSIST(ctx->stats[ctx->max_size].gets > 0U);
698 ctx->stats[ctx->max_size].gets--;
699 } else {
700 INSIST(ctx->stats[size].gets > 0U);
701 ctx->stats[size].gets--;
702 }
703 #if ISC_MEM_CHECKOVERRUN
704 size += 1;
705 #endif /* if ISC_MEM_CHECKOVERRUN */
706 ctx->malloced -= size;
707 }
708
709 /*
710 * Private.
711 */
712
713 static void *
714 default_memalloc(size_t size) {
715 void *ptr;
716
717 ptr = malloc(size);
718
719 /*
720 * If the space cannot be allocated, a null pointer is returned. If the
721 * size of the space requested is zero, the behavior is
722 * implementation-defined: either a null pointer is returned, or the
723 * behavior is as if the size were some nonzero value, except that the
724 * returned pointer shall not be used to access an object.
725 * [ISO9899 7.22.3]
726 *
727 * [ISO9899]
728 * ISO/IEC WG 9899:2011: Programming languages - C.
729 * International Organization for Standardization, Geneva,
730 * Switzerland.
731 * http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1570.pdf
732 */
733
734 if (ptr == NULL && size != 0) {
735 char strbuf[ISC_STRERRORSIZE];
736 strerror_r(errno, strbuf, sizeof(strbuf));
737 isc_error_fatal(__FILE__, __LINE__, "malloc failed: %s",
738 strbuf);
739 }
740
741 return (ptr);
742 }
743
744 static void
745 default_memfree(void *ptr) {
746 free(ptr);
747 }
748
749 static void
750 mem_initialize(void) {
751 isc_mutex_init(&contextslock);
752 ISC_LIST_INIT(contexts);
753 totallost = 0;
754 }
755
756 void
757 isc__mem_initialize(void) {
758 RUNTIME_CHECK(isc_once_do(&init_once, mem_initialize) == ISC_R_SUCCESS);
759 }
760
761 static void
762 mem_shutdown(void) {
763 isc__mem_checkdestroyed();
764
765 isc_mutex_destroy(&contextslock);
766 }
767
768 void
769 isc__mem_shutdown(void) {
770 RUNTIME_CHECK(isc_once_do(&shut_once, mem_shutdown) == ISC_R_SUCCESS);
771 }
772
773 static void
774 mem_create(isc_mem_t **ctxp, unsigned int flags) {
775 REQUIRE(ctxp != NULL && *ctxp == NULL);
776 #if __SANITIZE_ADDRESS__
777 REQUIRE((flags & ISC_MEMFLAG_INTERNAL) == 0);
778 #endif
779
780 isc__mem_t *ctx;
781
782 isc_enable_constructors();
783
784 STATIC_ASSERT((ALIGNMENT_SIZE & (ALIGNMENT_SIZE - 1)) == 0,
785 "wrong alignment size");
786
787 ctx = (default_memalloc)(sizeof(*ctx));
788
789 isc_mutex_init(&ctx->lock);
790
791 ctx->max_size = DEF_MAX_SIZE;
792 ctx->flags = flags;
793 isc_refcount_init(&ctx->references, 1);
794 memset(ctx->name, 0, sizeof(ctx->name));
795 ctx->tag = NULL;
796 ctx->total = 0;
797 ctx->inuse = 0;
798 ctx->maxinuse = 0;
799 ctx->malloced = sizeof(*ctx);
800 ctx->maxmalloced = sizeof(*ctx);
801 ctx->hi_water = 0;
802 ctx->lo_water = 0;
803 ctx->hi_called = false;
804 ctx->is_overmem = false;
805 ctx->water = NULL;
806 ctx->water_arg = NULL;
807 ctx->common.impmagic = MEM_MAGIC;
808 ctx->common.magic = ISCAPI_MCTX_MAGIC;
809 ctx->common.methods = (isc_memmethods_t *)&memmethods;
810 ctx->memalloc = default_memalloc;
811 ctx->memfree = default_memfree;
812 ctx->stats = NULL;
813 ctx->checkfree = true;
814 #if ISC_MEM_TRACKLINES
815 ctx->debuglist = NULL;
816 ctx->debuglistcnt = 0;
817 #endif /* if ISC_MEM_TRACKLINES */
818 ISC_LIST_INIT(ctx->pools);
819 ctx->poolcnt = 0;
820 ctx->freelists = NULL;
821 ctx->basic_blocks = NULL;
822 ctx->basic_table = NULL;
823 ctx->basic_table_count = 0;
824 ctx->basic_table_size = 0;
825 ctx->lowest = NULL;
826 ctx->highest = NULL;
827
828 ctx->stats =
829 (ctx->memalloc)((ctx->max_size + 1) * sizeof(struct stats));
830
831 memset(ctx->stats, 0, (ctx->max_size + 1) * sizeof(struct stats));
832 ctx->malloced += (ctx->max_size + 1) * sizeof(struct stats);
833 ctx->maxmalloced += (ctx->max_size + 1) * sizeof(struct stats);
834
835 if ((flags & ISC_MEMFLAG_INTERNAL) != 0) {
836 ctx->mem_target = DEF_MEM_TARGET;
837 ctx->freelists =
838 (ctx->memalloc)(ctx->max_size * sizeof(element *));
839 memset(ctx->freelists, 0, ctx->max_size * sizeof(element *));
840 ctx->malloced += ctx->max_size * sizeof(element *);
841 ctx->maxmalloced += ctx->max_size * sizeof(element *);
842 }
843
844 #if ISC_MEM_TRACKLINES
845 if (ISC_UNLIKELY((isc_mem_debugging & ISC_MEM_DEBUGRECORD) != 0)) {
846 unsigned int i;
847
848 ctx->debuglist = (ctx->memalloc)(
849 (DEBUG_TABLE_COUNT * sizeof(debuglist_t)));
850 for (i = 0; i < DEBUG_TABLE_COUNT; i++) {
851 ISC_LIST_INIT(ctx->debuglist[i]);
852 }
853 ctx->malloced += DEBUG_TABLE_COUNT * sizeof(debuglist_t);
854 ctx->maxmalloced += DEBUG_TABLE_COUNT * sizeof(debuglist_t);
855 }
856 #endif /* if ISC_MEM_TRACKLINES */
857
858 LOCK(&contextslock);
859 ISC_LIST_INITANDAPPEND(contexts, ctx, link);
860 UNLOCK(&contextslock);
861
862 *ctxp = (isc_mem_t *)ctx;
863 }
864
865 /*
866 * Public.
867 */
868
869 static void
870 destroy(isc__mem_t *ctx) {
871 unsigned int i;
872
873 LOCK(&contextslock);
874 ISC_LIST_UNLINK(contexts, ctx, link);
875 totallost += ctx->inuse;
876 UNLOCK(&contextslock);
877
878 ctx->common.impmagic = 0;
879 ctx->common.magic = 0;
880
881 INSIST(ISC_LIST_EMPTY(ctx->pools));
882
883 #if ISC_MEM_TRACKLINES
884 if (ISC_UNLIKELY(ctx->debuglist != NULL)) {
885 debuglink_t *dl;
886 for (i = 0; i < DEBUG_TABLE_COUNT; i++) {
887 for (dl = ISC_LIST_HEAD(ctx->debuglist[i]); dl != NULL;
888 dl = ISC_LIST_HEAD(ctx->debuglist[i]))
889 {
890 if (ctx->checkfree && dl->ptr != NULL) {
891 print_active(ctx, stderr);
892 }
893 INSIST(!ctx->checkfree || dl->ptr == NULL);
894
895 ISC_LIST_UNLINK(ctx->debuglist[i], dl, link);
896 free(dl);
897 ctx->malloced -= sizeof(*dl);
898 }
899 }
900
901 (ctx->memfree)(ctx->debuglist);
902 ctx->malloced -= DEBUG_TABLE_COUNT * sizeof(debuglist_t);
903 }
904 #endif /* if ISC_MEM_TRACKLINES */
905
906 if (ctx->checkfree) {
907 for (i = 0; i <= ctx->max_size; i++) {
908 if (ctx->stats[i].gets != 0U) {
909 fprintf(stderr,
910 "Failing assertion due to probable "
911 "leaked memory in context %p (\"%s\") "
912 "(stats[%u].gets == %lu).\n",
913 ctx, ctx->name, i, ctx->stats[i].gets);
914 #if ISC_MEM_TRACKLINES
915 print_active(ctx, stderr);
916 #endif /* if ISC_MEM_TRACKLINES */
917 INSIST(ctx->stats[i].gets == 0U);
918 }
919 }
920 }
921
922 (ctx->memfree)(ctx->stats);
923 ctx->malloced -= (ctx->max_size + 1) * sizeof(struct stats);
924
925 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
926 for (i = 0; i < ctx->basic_table_count; i++) {
927 (ctx->memfree)(ctx->basic_table[i]);
928 ctx->malloced -= NUM_BASIC_BLOCKS * ctx->mem_target;
929 }
930 (ctx->memfree)(ctx->freelists);
931 ctx->malloced -= ctx->max_size * sizeof(element *);
932 if (ctx->basic_table != NULL) {
933 (ctx->memfree)(ctx->basic_table);
934 ctx->malloced -= ctx->basic_table_size *
935 sizeof(unsigned char *);
936 }
937 }
938
939 isc_mutex_destroy(&ctx->lock);
940
941 ctx->malloced -= sizeof(*ctx);
942 if (ctx->checkfree) {
943 INSIST(ctx->malloced == 0);
944 }
945 (ctx->memfree)(ctx);
946 }
947
948 void
949 isc_mem_attach(isc_mem_t *source0, isc_mem_t **targetp) {
950 REQUIRE(VALID_CONTEXT(source0));
951 REQUIRE(targetp != NULL && *targetp == NULL);
952
953 isc__mem_t *source = (isc__mem_t *)source0;
954
955 isc_refcount_increment(&source->references);
956
957 *targetp = (isc_mem_t *)source;
958 }
959
960 void
961 isc_mem_detach(isc_mem_t **ctxp) {
962 REQUIRE(ctxp != NULL && VALID_CONTEXT(*ctxp));
963
964 isc__mem_t *ctx = (isc__mem_t *)*ctxp;
965 *ctxp = NULL;
966
967 if (isc_refcount_decrement(&ctx->references) == 1) {
968 isc_refcount_destroy(&ctx->references);
969 destroy(ctx);
970 }
971 }
972
973 /*
974 * isc_mem_putanddetach() is the equivalent of:
975 *
976 * mctx = NULL;
977 * isc_mem_attach(ptr->mctx, &mctx);
978 * isc_mem_detach(&ptr->mctx);
979 * isc_mem_put(mctx, ptr, sizeof(*ptr);
980 * isc_mem_detach(&mctx);
981 */
982
983 void
984 isc___mem_putanddetach(isc_mem_t **ctxp, void *ptr, size_t size FLARG) {
985 REQUIRE(ctxp != NULL && VALID_CONTEXT(*ctxp));
986 REQUIRE(ptr != NULL);
987
988 isc__mem_t *ctx = (isc__mem_t *)*ctxp;
989 *ctxp = NULL;
990
991 if (ISC_UNLIKELY((isc_mem_debugging &
992 (ISC_MEM_DEBUGSIZE | ISC_MEM_DEBUGCTX)) != 0))
993 {
994 if ((isc_mem_debugging & ISC_MEM_DEBUGSIZE) != 0) {
995 size_info *si = &(((size_info *)ptr)[-1]);
996 size_t oldsize = si->u.size - ALIGNMENT_SIZE;
997 if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0) {
998 oldsize -= ALIGNMENT_SIZE;
999 }
1000 INSIST(oldsize == size);
1001 }
1002 isc__mem_free((isc_mem_t *)ctx, ptr FLARG_PASS);
1003
1004 goto destroy;
1005 }
1006
1007 MCTXLOCK(ctx);
1008
1009 DELETE_TRACE(ctx, ptr, size, file, line);
1010
1011 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1012 mem_putunlocked(ctx, ptr, size);
1013 } else {
1014 mem_putstats(ctx, ptr, size);
1015 mem_put(ctx, ptr, size);
1016 }
1017 MCTXUNLOCK(ctx);
1018
1019 destroy:
1020 if (isc_refcount_decrement(&ctx->references) == 1) {
1021 isc_refcount_destroy(&ctx->references);
1022 destroy(ctx);
1023 }
1024 }
1025
1026 void
1027 isc_mem_destroy(isc_mem_t **ctxp) {
1028 /*
1029 * This routine provides legacy support for callers who use mctxs
1030 * without attaching/detaching.
1031 */
1032
1033 REQUIRE(ctxp != NULL && VALID_CONTEXT(*ctxp));
1034
1035 isc__mem_t *ctx = (isc__mem_t *)*ctxp;
1036
1037 #if ISC_MEM_TRACKLINES
1038 if (isc_refcount_decrement(&ctx->references) > 1) {
1039 print_active(ctx, stderr);
1040 }
1041 #else /* if ISC_MEM_TRACKLINES */
1042 isc_refcount_decrementz(&ctx->references);
1043 #endif /* if ISC_MEM_TRACKLINES */
1044 isc_refcount_destroy(&ctx->references);
1045 destroy(ctx);
1046
1047 *ctxp = NULL;
1048 }
1049
1050 void *
1051 isc___mem_get(isc_mem_t *ctx0, size_t size FLARG) {
1052 REQUIRE(VALID_CONTEXT(ctx0));
1053
1054 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1055 void *ptr;
1056 bool call_water = false;
1057
1058 if (ISC_UNLIKELY((isc_mem_debugging &
1059 (ISC_MEM_DEBUGSIZE | ISC_MEM_DEBUGCTX)) != 0))
1060 {
1061 return (isc__mem_allocate(ctx0, size FLARG_PASS));
1062 }
1063
1064 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1065 MCTXLOCK(ctx);
1066 ptr = mem_getunlocked(ctx, size);
1067 } else {
1068 ptr = mem_get(ctx, size);
1069 MCTXLOCK(ctx);
1070 if (ptr != NULL) {
1071 mem_getstats(ctx, size);
1072 }
1073 }
1074
1075 ADD_TRACE(ctx, ptr, size, file, line);
1076
1077 if (ctx->hi_water != 0U && ctx->inuse > ctx->hi_water) {
1078 ctx->is_overmem = true;
1079 if (!ctx->hi_called) {
1080 call_water = true;
1081 }
1082 }
1083 if (ctx->inuse > ctx->maxinuse) {
1084 ctx->maxinuse = ctx->inuse;
1085 if (ctx->hi_water != 0U && ctx->inuse > ctx->hi_water &&
1086 (isc_mem_debugging & ISC_MEM_DEBUGUSAGE) != 0)
1087 {
1088 fprintf(stderr, "maxinuse = %lu\n",
1089 (unsigned long)ctx->inuse);
1090 }
1091 }
1092 MCTXUNLOCK(ctx);
1093
1094 if (call_water && (ctx->water != NULL)) {
1095 (ctx->water)(ctx->water_arg, ISC_MEM_HIWATER);
1096 }
1097
1098 return (ptr);
1099 }
1100
1101 void
1102 isc___mem_put(isc_mem_t *ctx0, void *ptr, size_t size FLARG) {
1103 REQUIRE(VALID_CONTEXT(ctx0));
1104 REQUIRE(ptr != NULL);
1105
1106 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1107 bool call_water = false;
1108 size_info *si;
1109 size_t oldsize;
1110
1111 if (ISC_UNLIKELY((isc_mem_debugging &
1112 (ISC_MEM_DEBUGSIZE | ISC_MEM_DEBUGCTX)) != 0))
1113 {
1114 if ((isc_mem_debugging & ISC_MEM_DEBUGSIZE) != 0) {
1115 si = &(((size_info *)ptr)[-1]);
1116 oldsize = si->u.size - ALIGNMENT_SIZE;
1117 if ((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0) {
1118 oldsize -= ALIGNMENT_SIZE;
1119 }
1120 INSIST(oldsize == size);
1121 }
1122 isc__mem_free((isc_mem_t *)ctx, ptr FLARG_PASS);
1123 return;
1124 }
1125
1126 MCTXLOCK(ctx);
1127
1128 DELETE_TRACE(ctx, ptr, size, file, line);
1129
1130 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1131 mem_putunlocked(ctx, ptr, size);
1132 } else {
1133 mem_putstats(ctx, ptr, size);
1134 mem_put(ctx, ptr, size);
1135 }
1136
1137 /*
1138 * The check against ctx->lo_water == 0 is for the condition
1139 * when the context was pushed over hi_water but then had
1140 * isc_mem_setwater() called with 0 for hi_water and lo_water.
1141 */
1142 if ((ctx->inuse < ctx->lo_water) || (ctx->lo_water == 0U)) {
1143 ctx->is_overmem = false;
1144 if (ctx->hi_called) {
1145 call_water = true;
1146 }
1147 }
1148
1149 MCTXUNLOCK(ctx);
1150
1151 if (call_water && (ctx->water != NULL)) {
1152 (ctx->water)(ctx->water_arg, ISC_MEM_LOWATER);
1153 }
1154 }
1155
1156 void
1157 isc_mem_waterack(isc_mem_t *ctx0, int flag) {
1158 REQUIRE(VALID_CONTEXT(ctx0));
1159
1160 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1161
1162 MCTXLOCK(ctx);
1163 if (flag == ISC_MEM_LOWATER) {
1164 ctx->hi_called = false;
1165 } else if (flag == ISC_MEM_HIWATER) {
1166 ctx->hi_called = true;
1167 }
1168 MCTXUNLOCK(ctx);
1169 }
1170
1171 #if ISC_MEM_TRACKLINES
1172 static void
1173 print_active(isc__mem_t *mctx, FILE *out) {
1174 if (mctx->debuglist != NULL) {
1175 debuglink_t *dl;
1176 unsigned int i;
1177 bool found;
1178
1179 fputs("Dump of all outstanding memory allocations:\n", out);
1180 found = false;
1181 for (i = 0; i < DEBUG_TABLE_COUNT; i++) {
1182 dl = ISC_LIST_HEAD(mctx->debuglist[i]);
1183
1184 if (dl != NULL) {
1185 found = true;
1186 }
1187
1188 while (dl != NULL) {
1189 if (dl->ptr != NULL) {
1190 fprintf(out,
1191 "\tptr %p size %zu file %s "
1192 "line %u\n",
1193 dl->ptr, dl->size, dl->file,
1194 dl->line);
1195 }
1196 dl = ISC_LIST_NEXT(dl, link);
1197 }
1198 }
1199
1200 if (!found) {
1201 fputs("\tNone.\n", out);
1202 }
1203 }
1204 }
1205 #endif /* if ISC_MEM_TRACKLINES */
1206
1207 /*
1208 * Print the stats[] on the stream "out" with suitable formatting.
1209 */
1210 void
1211 isc_mem_stats(isc_mem_t *ctx0, FILE *out) {
1212 REQUIRE(VALID_CONTEXT(ctx0));
1213
1214 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1215 size_t i;
1216 const struct stats *s;
1217 const isc__mempool_t *pool;
1218
1219 MCTXLOCK(ctx);
1220
1221 for (i = 0; i <= ctx->max_size; i++) {
1222 s = &ctx->stats[i];
1223
1224 if (s->totalgets == 0U && s->gets == 0U) {
1225 continue;
1226 }
1227 fprintf(out, "%s%5lu: %11lu gets, %11lu rem",
1228 (i == ctx->max_size) ? ">=" : " ", (unsigned long)i,
1229 s->totalgets, s->gets);
1230 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0 &&
1231 (s->blocks != 0U || s->freefrags != 0U))
1232 {
1233 fprintf(out, " (%lu bl, %lu ff)", s->blocks,
1234 s->freefrags);
1235 }
1236 fputc('\n', out);
1237 }
1238
1239 /*
1240 * Note that since a pool can be locked now, these stats might be
1241 * somewhat off if the pool is in active use at the time the stats
1242 * are dumped. The link fields are protected by the isc_mem_t's
1243 * lock, however, so walking this list and extracting integers from
1244 * stats fields is always safe.
1245 */
1246 pool = ISC_LIST_HEAD(ctx->pools);
1247 if (pool != NULL) {
1248 fputs("[Pool statistics]\n", out);
1249 fprintf(out, "%15s %10s %10s %10s %10s %10s %10s %10s %1s\n",
1250 "name", "size", "maxalloc", "allocated", "freecount",
1251 "freemax", "fillcount", "gets", "L");
1252 }
1253 while (pool != NULL) {
1254 fprintf(out, "%15s %10lu %10u %10u %10u %10u %10u %10u %s\n",
1255 #if ISC_MEMPOOL_NAMES
1256 pool->name,
1257 #else /* if ISC_MEMPOOL_NAMES */
1258 "(not tracked)",
1259 #endif /* if ISC_MEMPOOL_NAMES */
1260 (unsigned long)pool->size, pool->maxalloc,
1261 pool->allocated, pool->freecount, pool->freemax,
1262 pool->fillcount, pool->gets,
1263 (pool->lock == NULL ? "N" : "Y"));
1264 pool = ISC_LIST_NEXT(pool, link);
1265 }
1266
1267 #if ISC_MEM_TRACKLINES
1268 print_active(ctx, out);
1269 #endif /* if ISC_MEM_TRACKLINES */
1270
1271 MCTXUNLOCK(ctx);
1272 }
1273
1274 /*
1275 * Replacements for malloc() and free() -- they implicitly remember the
1276 * size of the object allocated (with some additional overhead).
1277 */
1278
1279 static void *
1280 mem_allocateunlocked(isc_mem_t *ctx0, size_t size) {
1281 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1282 size_info *si;
1283
1284 size += ALIGNMENT_SIZE;
1285 if (ISC_UNLIKELY((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)) {
1286 size += ALIGNMENT_SIZE;
1287 }
1288
1289 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1290 si = mem_getunlocked(ctx, size);
1291 } else {
1292 si = mem_get(ctx, size);
1293 }
1294
1295 if (ISC_UNLIKELY((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)) {
1296 si->u.ctx = ctx;
1297 si++;
1298 }
1299 si->u.size = size;
1300 return (&si[1]);
1301 }
1302
1303 void *
1304 isc___mem_allocate(isc_mem_t *ctx0, size_t size FLARG) {
1305 REQUIRE(VALID_CONTEXT(ctx0));
1306
1307 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1308 size_info *si;
1309 bool call_water = false;
1310
1311 MCTXLOCK(ctx);
1312 si = mem_allocateunlocked((isc_mem_t *)ctx, size);
1313 if (((ctx->flags & ISC_MEMFLAG_INTERNAL) == 0)) {
1314 mem_getstats(ctx, si[-1].u.size);
1315 }
1316
1317 ADD_TRACE(ctx, si, si[-1].u.size, file, line);
1318 if (ctx->hi_water != 0U && ctx->inuse > ctx->hi_water &&
1319 !ctx->is_overmem) {
1320 ctx->is_overmem = true;
1321 }
1322
1323 if (ctx->hi_water != 0U && !ctx->hi_called &&
1324 ctx->inuse > ctx->hi_water) {
1325 ctx->hi_called = true;
1326 call_water = true;
1327 }
1328 if (ctx->inuse > ctx->maxinuse) {
1329 ctx->maxinuse = ctx->inuse;
1330 if (ISC_UNLIKELY(ctx->hi_water != 0U &&
1331 ctx->inuse > ctx->hi_water &&
1332 (isc_mem_debugging & ISC_MEM_DEBUGUSAGE) != 0))
1333 {
1334 fprintf(stderr, "maxinuse = %lu\n",
1335 (unsigned long)ctx->inuse);
1336 }
1337 }
1338 MCTXUNLOCK(ctx);
1339
1340 if (call_water) {
1341 (ctx->water)(ctx->water_arg, ISC_MEM_HIWATER);
1342 }
1343
1344 return (si);
1345 }
1346
1347 void *
1348 isc___mem_reallocate(isc_mem_t *ctx0, void *ptr, size_t size FLARG) {
1349 REQUIRE(VALID_CONTEXT(ctx0));
1350
1351 void *new_ptr = NULL;
1352 size_t oldsize, copysize;
1353
1354 /*
1355 * This function emulates the realloc(3) standard library function:
1356 * - if size > 0, allocate new memory; and if ptr is non NULL, copy
1357 * as much of the old contents to the new buffer and free the old one.
1358 * Note that when allocation fails the original pointer is intact;
1359 * the caller must free it.
1360 * - if size is 0 and ptr is non NULL, simply free the given ptr.
1361 * - this function returns:
1362 * pointer to the newly allocated memory, or
1363 * NULL if allocation fails or doesn't happen.
1364 */
1365 if (size > 0U) {
1366 new_ptr = isc__mem_allocate(ctx0, size FLARG_PASS);
1367 if (new_ptr != NULL && ptr != NULL) {
1368 oldsize = (((size_info *)ptr)[-1]).u.size;
1369 INSIST(oldsize >= ALIGNMENT_SIZE);
1370 oldsize -= ALIGNMENT_SIZE;
1371 if (ISC_UNLIKELY((isc_mem_debugging &
1372 ISC_MEM_DEBUGCTX) != 0)) {
1373 INSIST(oldsize >= ALIGNMENT_SIZE);
1374 oldsize -= ALIGNMENT_SIZE;
1375 }
1376 copysize = (oldsize > size) ? size : oldsize;
1377 memmove(new_ptr, ptr, copysize);
1378 isc__mem_free(ctx0, ptr FLARG_PASS);
1379 }
1380 } else if (ptr != NULL) {
1381 isc__mem_free(ctx0, ptr FLARG_PASS);
1382 }
1383
1384 return (new_ptr);
1385 }
1386
1387 void
1388 isc___mem_free(isc_mem_t *ctx0, void *ptr FLARG) {
1389 REQUIRE(VALID_CONTEXT(ctx0));
1390 REQUIRE(ptr != NULL);
1391
1392 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1393 size_info *si;
1394 size_t size;
1395 bool call_water = false;
1396
1397 if (ISC_UNLIKELY((isc_mem_debugging & ISC_MEM_DEBUGCTX) != 0)) {
1398 si = &(((size_info *)ptr)[-2]);
1399 REQUIRE(si->u.ctx == ctx);
1400 size = si[1].u.size;
1401 } else {
1402 si = &(((size_info *)ptr)[-1]);
1403 size = si->u.size;
1404 }
1405
1406 MCTXLOCK(ctx);
1407
1408 DELETE_TRACE(ctx, ptr, size, file, line);
1409
1410 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1411 mem_putunlocked(ctx, si, size);
1412 } else {
1413 mem_putstats(ctx, si, size);
1414 mem_put(ctx, si, size);
1415 }
1416
1417 /*
1418 * The check against ctx->lo_water == 0 is for the condition
1419 * when the context was pushed over hi_water but then had
1420 * isc_mem_setwater() called with 0 for hi_water and lo_water.
1421 */
1422 if (ctx->is_overmem &&
1423 (ctx->inuse < ctx->lo_water || ctx->lo_water == 0U)) {
1424 ctx->is_overmem = false;
1425 }
1426
1427 if (ctx->hi_called &&
1428 (ctx->inuse < ctx->lo_water || ctx->lo_water == 0U)) {
1429 ctx->hi_called = false;
1430
1431 if (ctx->water != NULL) {
1432 call_water = true;
1433 }
1434 }
1435 MCTXUNLOCK(ctx);
1436
1437 if (call_water) {
1438 (ctx->water)(ctx->water_arg, ISC_MEM_LOWATER);
1439 }
1440 }
1441
1442 /*
1443 * Other useful things.
1444 */
1445
1446 char *
1447 isc___mem_strdup(isc_mem_t *mctx0, const char *s FLARG) {
1448 REQUIRE(VALID_CONTEXT(mctx0));
1449 REQUIRE(s != NULL);
1450
1451 isc__mem_t *mctx = (isc__mem_t *)mctx0;
1452 size_t len;
1453 char *ns;
1454
1455 len = strlen(s) + 1;
1456
1457 ns = isc__mem_allocate((isc_mem_t *)mctx, len FLARG_PASS);
1458
1459 if (ns != NULL) {
1460 strlcpy(ns, s, len);
1461 }
1462
1463 return (ns);
1464 }
1465
1466 void
1467 isc_mem_setdestroycheck(isc_mem_t *ctx0, bool flag) {
1468 REQUIRE(VALID_CONTEXT(ctx0));
1469
1470 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1471
1472 MCTXLOCK(ctx);
1473
1474 ctx->checkfree = flag;
1475
1476 MCTXUNLOCK(ctx);
1477 }
1478
1479 size_t
1480 isc_mem_inuse(isc_mem_t *ctx0) {
1481 REQUIRE(VALID_CONTEXT(ctx0));
1482
1483 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1484 size_t inuse;
1485
1486 MCTXLOCK(ctx);
1487
1488 inuse = ctx->inuse;
1489
1490 MCTXUNLOCK(ctx);
1491
1492 return (inuse);
1493 }
1494
1495 size_t
1496 isc_mem_maxinuse(isc_mem_t *ctx0) {
1497 REQUIRE(VALID_CONTEXT(ctx0));
1498
1499 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1500 size_t maxinuse;
1501
1502 MCTXLOCK(ctx);
1503
1504 maxinuse = ctx->maxinuse;
1505
1506 MCTXUNLOCK(ctx);
1507
1508 return (maxinuse);
1509 }
1510
1511 size_t
1512 isc_mem_total(isc_mem_t *ctx0) {
1513 REQUIRE(VALID_CONTEXT(ctx0));
1514
1515 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1516 size_t total;
1517
1518 MCTXLOCK(ctx);
1519
1520 total = ctx->total;
1521
1522 MCTXUNLOCK(ctx);
1523
1524 return (total);
1525 }
1526
1527 void
1528 isc_mem_setwater(isc_mem_t *ctx0, isc_mem_water_t water, void *water_arg,
1529 size_t hiwater, size_t lowater) {
1530 REQUIRE(VALID_CONTEXT(ctx0));
1531 REQUIRE(hiwater >= lowater);
1532
1533 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1534 bool callwater = false;
1535 isc_mem_water_t oldwater;
1536 void *oldwater_arg;
1537
1538 MCTXLOCK(ctx);
1539 oldwater = ctx->water;
1540 oldwater_arg = ctx->water_arg;
1541 if (water == NULL) {
1542 callwater = ctx->hi_called;
1543 ctx->water = NULL;
1544 ctx->water_arg = NULL;
1545 ctx->hi_water = 0;
1546 ctx->lo_water = 0;
1547 } else {
1548 if (ctx->hi_called &&
1549 (ctx->water != water || ctx->water_arg != water_arg ||
1550 ctx->inuse < lowater || lowater == 0U))
1551 {
1552 callwater = true;
1553 }
1554 ctx->water = water;
1555 ctx->water_arg = water_arg;
1556 ctx->hi_water = hiwater;
1557 ctx->lo_water = lowater;
1558 }
1559 MCTXUNLOCK(ctx);
1560
1561 if (callwater && oldwater != NULL) {
1562 (oldwater)(oldwater_arg, ISC_MEM_LOWATER);
1563 }
1564 }
1565
1566 ISC_NO_SANITIZE_THREAD bool
1567 isc_mem_isovermem(isc_mem_t *ctx0) {
1568 REQUIRE(VALID_CONTEXT(ctx0));
1569
1570 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1571
1572 /*
1573 * We don't bother to lock the context because 100% accuracy isn't
1574 * necessary (and even if we locked the context the returned value
1575 * could be different from the actual state when it's used anyway)
1576 */
1577 return (ctx->is_overmem);
1578 }
1579
1580 void
1581 isc_mem_setname(isc_mem_t *ctx0, const char *name, void *tag) {
1582 REQUIRE(VALID_CONTEXT(ctx0));
1583
1584 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1585
1586 LOCK(&ctx->lock);
1587 strlcpy(ctx->name, name, sizeof(ctx->name));
1588 ctx->tag = tag;
1589 UNLOCK(&ctx->lock);
1590 }
1591
1592 const char *
1593 isc_mem_getname(isc_mem_t *ctx0) {
1594 REQUIRE(VALID_CONTEXT(ctx0));
1595
1596 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1597
1598 if (ctx->name[0] == 0) {
1599 return ("");
1600 }
1601
1602 return (ctx->name);
1603 }
1604
1605 void *
1606 isc_mem_gettag(isc_mem_t *ctx0) {
1607 REQUIRE(VALID_CONTEXT(ctx0));
1608
1609 isc__mem_t *ctx = (isc__mem_t *)ctx0;
1610
1611 return (ctx->tag);
1612 }
1613
1614 /*
1615 * Memory pool stuff
1616 */
1617
1618 void
1619 isc_mempool_create(isc_mem_t *mctx0, size_t size, isc_mempool_t **mpctxp) {
1620 REQUIRE(VALID_CONTEXT(mctx0));
1621 REQUIRE(size > 0U);
1622 REQUIRE(mpctxp != NULL && *mpctxp == NULL);
1623
1624 isc__mem_t *mctx = (isc__mem_t *)mctx0;
1625 isc__mempool_t *mpctx;
1626
1627 /*
1628 * Allocate space for this pool, initialize values, and if all works
1629 * well, attach to the memory context.
1630 */
1631 mpctx = isc_mem_get((isc_mem_t *)mctx, sizeof(isc__mempool_t));
1632
1633 mpctx->common.impmagic = MEMPOOL_MAGIC;
1634 mpctx->common.magic = ISCAPI_MPOOL_MAGIC;
1635 mpctx->lock = NULL;
1636 mpctx->mctx = mctx;
1637 /*
1638 * Mempools are stored as a linked list of element.
1639 */
1640 if (size < sizeof(element)) {
1641 size = sizeof(element);
1642 }
1643 mpctx->size = size;
1644 mpctx->maxalloc = UINT_MAX;
1645 mpctx->allocated = 0;
1646 mpctx->freecount = 0;
1647 mpctx->freemax = 1;
1648 mpctx->fillcount = 1;
1649 mpctx->gets = 0;
1650 #if ISC_MEMPOOL_NAMES
1651 mpctx->name[0] = 0;
1652 #endif /* if ISC_MEMPOOL_NAMES */
1653 mpctx->items = NULL;
1654
1655 *mpctxp = (isc_mempool_t *)mpctx;
1656
1657 MCTXLOCK(mctx);
1658 ISC_LIST_INITANDAPPEND(mctx->pools, mpctx, link);
1659 mctx->poolcnt++;
1660 MCTXUNLOCK(mctx);
1661 }
1662
1663 void
1664 isc_mempool_setname(isc_mempool_t *mpctx0, const char *name) {
1665 REQUIRE(VALID_MEMPOOL(mpctx0));
1666 REQUIRE(name != NULL);
1667
1668 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1669
1670 #if ISC_MEMPOOL_NAMES
1671 if (mpctx->lock != NULL) {
1672 LOCK(mpctx->lock);
1673 }
1674
1675 strlcpy(mpctx->name, name, sizeof(mpctx->name));
1676
1677 if (mpctx->lock != NULL) {
1678 UNLOCK(mpctx->lock);
1679 }
1680 #else /* if ISC_MEMPOOL_NAMES */
1681 UNUSED(mpctx);
1682 UNUSED(name);
1683 #endif /* if ISC_MEMPOOL_NAMES */
1684 }
1685
1686 void
1687 isc_mempool_destroy(isc_mempool_t **mpctxp) {
1688 REQUIRE(mpctxp != NULL);
1689 REQUIRE(VALID_MEMPOOL(*mpctxp));
1690
1691 isc__mempool_t *mpctx;
1692 isc__mem_t *mctx;
1693 isc_mutex_t *lock;
1694 element *item;
1695
1696 mpctx = (isc__mempool_t *)*mpctxp;
1697 #if ISC_MEMPOOL_NAMES
1698 if (mpctx->allocated > 0) {
1699 UNEXPECTED_ERROR(__FILE__, __LINE__,
1700 "isc_mempool_destroy(): mempool %s "
1701 "leaked memory",
1702 mpctx->name);
1703 }
1704 #endif /* if ISC_MEMPOOL_NAMES */
1705 REQUIRE(mpctx->allocated == 0);
1706
1707 mctx = mpctx->mctx;
1708
1709 lock = mpctx->lock;
1710
1711 if (lock != NULL) {
1712 LOCK(lock);
1713 }
1714
1715 /*
1716 * Return any items on the free list
1717 */
1718 MCTXLOCK(mctx);
1719 while (mpctx->items != NULL) {
1720 INSIST(mpctx->freecount > 0);
1721 mpctx->freecount--;
1722 item = mpctx->items;
1723 mpctx->items = item->next;
1724
1725 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1726 mem_putunlocked(mctx, item, mpctx->size);
1727 } else {
1728 mem_putstats(mctx, item, mpctx->size);
1729 mem_put(mctx, item, mpctx->size);
1730 }
1731 }
1732 MCTXUNLOCK(mctx);
1733
1734 /*
1735 * Remove our linked list entry from the memory context.
1736 */
1737 MCTXLOCK(mctx);
1738 ISC_LIST_UNLINK(mctx->pools, mpctx, link);
1739 mctx->poolcnt--;
1740 MCTXUNLOCK(mctx);
1741
1742 mpctx->common.impmagic = 0;
1743 mpctx->common.magic = 0;
1744
1745 isc_mem_put((isc_mem_t *)mpctx->mctx, mpctx, sizeof(isc__mempool_t));
1746
1747 if (lock != NULL) {
1748 UNLOCK(lock);
1749 }
1750
1751 *mpctxp = NULL;
1752 }
1753
1754 void
1755 isc_mempool_associatelock(isc_mempool_t *mpctx0, isc_mutex_t *lock) {
1756 REQUIRE(VALID_MEMPOOL(mpctx0));
1757 REQUIRE(lock != NULL);
1758
1759 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1760
1761 REQUIRE(mpctx->lock == NULL);
1762
1763 mpctx->lock = lock;
1764 }
1765
1766 #if __SANITIZE_ADDRESS__
1767 void *
1768 isc__mempool_get(isc_mempool_t *mpctx0 FLARG) {
1769 void *item = NULL;
1770
1771 REQUIRE(VALID_MEMPOOL(mpctx0));
1772
1773 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1774 isc_mem_t *mctx = (isc_mem_t *)mpctx->mctx;
1775
1776 if (mpctx->lock != NULL) {
1777 LOCK(mpctx->lock);
1778 }
1779
1780 /*
1781 * Don't let the caller go over quota
1782 */
1783 if (ISC_UNLIKELY(mpctx->allocated >= mpctx->maxalloc)) {
1784 goto out;
1785 }
1786
1787 item = isc__mem_get(mctx, mpctx->size FLARG_PASS);
1788 mpctx->gets++;
1789 mpctx->allocated++;
1790
1791 out:
1792 if (mpctx->lock != NULL) {
1793 UNLOCK(mpctx->lock);
1794 }
1795
1796 return (item);
1797 }
1798
1799 void
1800 isc__mempool_put(isc_mempool_t *mpctx0, void *mem FLARG) {
1801 REQUIRE(VALID_MEMPOOL(mpctx0));
1802
1803 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1804 isc_mem_t *mctx = (isc_mem_t *)mpctx->mctx;
1805
1806 REQUIRE(mem != NULL);
1807
1808 if (mpctx->lock != NULL) {
1809 LOCK(mpctx->lock);
1810 }
1811
1812 INSIST(mpctx->allocated > 0);
1813 mpctx->allocated--;
1814
1815 isc__mem_put(mctx, mem, mpctx->size FLARG_PASS);
1816
1817 if (mpctx->lock != NULL) {
1818 UNLOCK(mpctx->lock);
1819 }
1820 }
1821
1822 #else /* __SANITIZE_ADDRESS__ */
1823 void *
1824 isc__mempool_get(isc_mempool_t *mpctx0 FLARG) {
1825 REQUIRE(VALID_MEMPOOL(mpctx0));
1826
1827 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1828 element *item;
1829 isc__mem_t *mctx;
1830 unsigned int i;
1831
1832 mctx = mpctx->mctx;
1833
1834 if (mpctx->lock != NULL) {
1835 LOCK(mpctx->lock);
1836 }
1837
1838 /*
1839 * Don't let the caller go over quota
1840 */
1841 if (ISC_UNLIKELY(mpctx->allocated >= mpctx->maxalloc)) {
1842 item = NULL;
1843 goto out;
1844 }
1845
1846 if (ISC_UNLIKELY(mpctx->items == NULL)) {
1847 /*
1848 * We need to dip into the well. Lock the memory context
1849 * here and fill up our free list.
1850 */
1851 MCTXLOCK(mctx);
1852 for (i = 0; i < mpctx->fillcount; i++) {
1853 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1854 item = mem_getunlocked(mctx, mpctx->size);
1855 } else {
1856 item = mem_get(mctx, mpctx->size);
1857 if (item != NULL) {
1858 mem_getstats(mctx, mpctx->size);
1859 }
1860 }
1861 if (ISC_UNLIKELY(item == NULL)) {
1862 break;
1863 }
1864 item->next = mpctx->items;
1865 mpctx->items = item;
1866 mpctx->freecount++;
1867 }
1868 MCTXUNLOCK(mctx);
1869 }
1870
1871 /*
1872 * If we didn't get any items, return NULL.
1873 */
1874 item = mpctx->items;
1875 if (ISC_UNLIKELY(item == NULL)) {
1876 goto out;
1877 }
1878
1879 mpctx->items = item->next;
1880 INSIST(mpctx->freecount > 0);
1881 mpctx->freecount--;
1882 mpctx->gets++;
1883 mpctx->allocated++;
1884
1885 out:
1886 if (mpctx->lock != NULL) {
1887 UNLOCK(mpctx->lock);
1888 }
1889
1890 #if ISC_MEM_TRACKLINES
1891 if (ISC_UNLIKELY(((isc_mem_debugging & TRACE_OR_RECORD) != 0) &&
1892 item != NULL)) {
1893 MCTXLOCK(mctx);
1894 ADD_TRACE(mctx, item, mpctx->size, file, line);
1895 MCTXUNLOCK(mctx);
1896 }
1897 #endif /* ISC_MEM_TRACKLINES */
1898
1899 return (item);
1900 }
1901
1902 /* coverity[+free : arg-1] */
1903 void
1904 isc__mempool_put(isc_mempool_t *mpctx0, void *mem FLARG) {
1905 REQUIRE(VALID_MEMPOOL(mpctx0));
1906 REQUIRE(mem != NULL);
1907
1908 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1909 isc__mem_t *mctx = mpctx->mctx;
1910 element *item;
1911
1912 if (mpctx->lock != NULL) {
1913 LOCK(mpctx->lock);
1914 }
1915
1916 INSIST(mpctx->allocated > 0);
1917 mpctx->allocated--;
1918
1919 #if ISC_MEM_TRACKLINES
1920 if (ISC_UNLIKELY((isc_mem_debugging & TRACE_OR_RECORD) != 0)) {
1921 MCTXLOCK(mctx);
1922 DELETE_TRACE(mctx, mem, mpctx->size, file, line);
1923 MCTXUNLOCK(mctx);
1924 }
1925 #endif /* ISC_MEM_TRACKLINES */
1926
1927 /*
1928 * If our free list is full, return this to the mctx directly.
1929 */
1930 if (mpctx->freecount >= mpctx->freemax) {
1931 MCTXLOCK(mctx);
1932 if ((mctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
1933 mem_putunlocked(mctx, mem, mpctx->size);
1934 } else {
1935 mem_putstats(mctx, mem, mpctx->size);
1936 mem_put(mctx, mem, mpctx->size);
1937 }
1938 MCTXUNLOCK(mctx);
1939 if (mpctx->lock != NULL) {
1940 UNLOCK(mpctx->lock);
1941 }
1942 return;
1943 }
1944
1945 /*
1946 * Otherwise, attach it to our free list and bump the counter.
1947 */
1948 mpctx->freecount++;
1949 item = (element *)mem;
1950 item->next = mpctx->items;
1951 mpctx->items = item;
1952
1953 if (mpctx->lock != NULL) {
1954 UNLOCK(mpctx->lock);
1955 }
1956 }
1957
1958 #endif /* __SANITIZE_ADDRESS__ */
1959
1960 /*
1961 * Quotas
1962 */
1963
1964 void
1965 isc_mempool_setfreemax(isc_mempool_t *mpctx0, unsigned int limit) {
1966 REQUIRE(VALID_MEMPOOL(mpctx0));
1967
1968 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1969
1970 if (mpctx->lock != NULL) {
1971 LOCK(mpctx->lock);
1972 }
1973
1974 mpctx->freemax = limit;
1975
1976 if (mpctx->lock != NULL) {
1977 UNLOCK(mpctx->lock);
1978 }
1979 }
1980
1981 unsigned int
1982 isc_mempool_getfreemax(isc_mempool_t *mpctx0) {
1983 REQUIRE(VALID_MEMPOOL(mpctx0));
1984
1985 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
1986 unsigned int freemax;
1987
1988 if (mpctx->lock != NULL) {
1989 LOCK(mpctx->lock);
1990 }
1991
1992 freemax = mpctx->freemax;
1993
1994 if (mpctx->lock != NULL) {
1995 UNLOCK(mpctx->lock);
1996 }
1997
1998 return (freemax);
1999 }
2000
2001 unsigned int
2002 isc_mempool_getfreecount(isc_mempool_t *mpctx0) {
2003 REQUIRE(VALID_MEMPOOL(mpctx0));
2004
2005 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2006 unsigned int freecount;
2007
2008 if (mpctx->lock != NULL) {
2009 LOCK(mpctx->lock);
2010 }
2011
2012 freecount = mpctx->freecount;
2013
2014 if (mpctx->lock != NULL) {
2015 UNLOCK(mpctx->lock);
2016 }
2017
2018 return (freecount);
2019 }
2020
2021 void
2022 isc_mempool_setmaxalloc(isc_mempool_t *mpctx0, unsigned int limit) {
2023 REQUIRE(VALID_MEMPOOL(mpctx0));
2024 REQUIRE(limit > 0);
2025
2026 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2027
2028 if (mpctx->lock != NULL) {
2029 LOCK(mpctx->lock);
2030 }
2031
2032 mpctx->maxalloc = limit;
2033
2034 if (mpctx->lock != NULL) {
2035 UNLOCK(mpctx->lock);
2036 }
2037 }
2038
2039 unsigned int
2040 isc_mempool_getmaxalloc(isc_mempool_t *mpctx0) {
2041 REQUIRE(VALID_MEMPOOL(mpctx0));
2042
2043 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2044 unsigned int maxalloc;
2045
2046 if (mpctx->lock != NULL) {
2047 LOCK(mpctx->lock);
2048 }
2049
2050 maxalloc = mpctx->maxalloc;
2051
2052 if (mpctx->lock != NULL) {
2053 UNLOCK(mpctx->lock);
2054 }
2055
2056 return (maxalloc);
2057 }
2058
2059 unsigned int
2060 isc_mempool_getallocated(isc_mempool_t *mpctx0) {
2061 REQUIRE(VALID_MEMPOOL(mpctx0));
2062
2063 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2064 unsigned int allocated;
2065
2066 if (mpctx->lock != NULL) {
2067 LOCK(mpctx->lock);
2068 }
2069
2070 allocated = mpctx->allocated;
2071
2072 if (mpctx->lock != NULL) {
2073 UNLOCK(mpctx->lock);
2074 }
2075
2076 return (allocated);
2077 }
2078
2079 void
2080 isc_mempool_setfillcount(isc_mempool_t *mpctx0, unsigned int limit) {
2081 REQUIRE(VALID_MEMPOOL(mpctx0));
2082 REQUIRE(limit > 0);
2083
2084 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2085
2086 if (mpctx->lock != NULL) {
2087 LOCK(mpctx->lock);
2088 }
2089
2090 mpctx->fillcount = limit;
2091
2092 if (mpctx->lock != NULL) {
2093 UNLOCK(mpctx->lock);
2094 }
2095 }
2096
2097 unsigned int
2098 isc_mempool_getfillcount(isc_mempool_t *mpctx0) {
2099 REQUIRE(VALID_MEMPOOL(mpctx0));
2100
2101 isc__mempool_t *mpctx = (isc__mempool_t *)mpctx0;
2102
2103 unsigned int fillcount;
2104
2105 if (mpctx->lock != NULL) {
2106 LOCK(mpctx->lock);
2107 }
2108
2109 fillcount = mpctx->fillcount;
2110
2111 if (mpctx->lock != NULL) {
2112 UNLOCK(mpctx->lock);
2113 }
2114
2115 return (fillcount);
2116 }
2117
2118 /*
2119 * Requires contextslock to be held by caller.
2120 */
2121 static void
2122 print_contexts(FILE *file) {
2123 isc__mem_t *ctx;
2124
2125 for (ctx = ISC_LIST_HEAD(contexts); ctx != NULL;
2126 ctx = ISC_LIST_NEXT(ctx, link)) {
2127 fprintf(file, "context: %p (%s): %" PRIuFAST32 " references\n",
2128 ctx, ctx->name[0] == 0 ? "<unknown>" : ctx->name,
2129 isc_refcount_current(&ctx->references));
2130 print_active(ctx, file);
2131 }
2132 fflush(file);
2133 }
2134
2135 static atomic_uintptr_t checkdestroyed = ATOMIC_VAR_INIT(0);
2136
2137 void
2138 isc_mem_checkdestroyed(FILE *file) {
2139 atomic_store_release(&checkdestroyed, (uintptr_t)file);
2140 }
2141
2142 void
2143 isc__mem_checkdestroyed(void) {
2144 FILE *file = (FILE *)atomic_load_acquire(&checkdestroyed);
2145
2146 if (file == NULL) {
2147 return;
2148 }
2149
2150 LOCK(&contextslock);
2151 if (!ISC_LIST_EMPTY(contexts)) {
2152 #if ISC_MEM_TRACKLINES
2153 if (ISC_UNLIKELY((isc_mem_debugging & TRACE_OR_RECORD) != 0)) {
2154 print_contexts(file);
2155 }
2156 #endif /* if ISC_MEM_TRACKLINES */
2157 INSIST(0);
2158 ISC_UNREACHABLE();
2159 }
2160 UNLOCK(&contextslock);
2161 }
2162
2163 unsigned int
2164 isc_mem_references(isc_mem_t *ctx0) {
2165 isc__mem_t *ctx = (isc__mem_t *)ctx0;
2166 return (isc_refcount_current(&ctx->references));
2167 }
2168
2169 typedef struct summarystat {
2170 uint64_t total;
2171 uint64_t inuse;
2172 uint64_t malloced;
2173 uint64_t blocksize;
2174 uint64_t contextsize;
2175 } summarystat_t;
2176
2177 #ifdef HAVE_LIBXML2
2178 #define TRY0(a) \
2179 do { \
2180 xmlrc = (a); \
2181 if (xmlrc < 0) \
2182 goto error; \
2183 } while (0)
2184 static int
2185 xml_renderctx(isc__mem_t *ctx, summarystat_t *summary,
2186 xmlTextWriterPtr writer) {
2187 REQUIRE(VALID_CONTEXT(ctx));
2188
2189 int xmlrc;
2190
2191 MCTXLOCK(ctx);
2192
2193 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "context"));
2194
2195 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "id"));
2196 TRY0(xmlTextWriterWriteFormatString(writer, "%p", ctx));
2197 TRY0(xmlTextWriterEndElement(writer)); /* id */
2198
2199 if (ctx->name[0] != 0) {
2200 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "name"));
2201 TRY0(xmlTextWriterWriteFormatString(writer, "%s", ctx->name));
2202 TRY0(xmlTextWriterEndElement(writer)); /* name */
2203 }
2204
2205 summary->contextsize += sizeof(*ctx) +
2206 (ctx->max_size + 1) * sizeof(struct stats) +
2207 ctx->max_size * sizeof(element *) +
2208 ctx->basic_table_count * sizeof(char *);
2209 #if ISC_MEM_TRACKLINES
2210 if (ctx->debuglist != NULL) {
2211 summary->contextsize += DEBUG_TABLE_COUNT *
2212 sizeof(debuglist_t) +
2213 ctx->debuglistcnt * sizeof(debuglink_t);
2214 }
2215 #endif /* if ISC_MEM_TRACKLINES */
2216 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "references"));
2217 TRY0(xmlTextWriterWriteFormatString(
2218 writer, "%" PRIuFAST32,
2219 isc_refcount_current(&ctx->references)));
2220 TRY0(xmlTextWriterEndElement(writer)); /* references */
2221
2222 summary->total += ctx->total;
2223 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "total"));
2224 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2225 (uint64_t)ctx->total));
2226 TRY0(xmlTextWriterEndElement(writer)); /* total */
2227
2228 summary->inuse += ctx->inuse;
2229 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "inuse"));
2230 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2231 (uint64_t)ctx->inuse));
2232 TRY0(xmlTextWriterEndElement(writer)); /* inuse */
2233
2234 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "maxinuse"));
2235 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2236 (uint64_t)ctx->maxinuse));
2237 TRY0(xmlTextWriterEndElement(writer)); /* maxinuse */
2238
2239 summary->malloced += ctx->malloced;
2240 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "malloced"));
2241 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2242 (uint64_t)ctx->malloced));
2243 TRY0(xmlTextWriterEndElement(writer)); /* malloced */
2244
2245 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "maxmalloced"));
2246 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2247 (uint64_t)ctx->maxmalloced));
2248 TRY0(xmlTextWriterEndElement(writer)); /* maxmalloced */
2249
2250 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "blocksize"));
2251 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
2252 summary->blocksize += ctx->basic_table_count *
2253 NUM_BASIC_BLOCKS * ctx->mem_target;
2254 TRY0(xmlTextWriterWriteFormatString(
2255 writer, "%" PRIu64 "",
2256 (uint64_t)ctx->basic_table_count * NUM_BASIC_BLOCKS *
2257 ctx->mem_target));
2258 } else {
2259 TRY0(xmlTextWriterWriteFormatString(writer, "%s", "-"));
2260 }
2261 TRY0(xmlTextWriterEndElement(writer)); /* blocksize */
2262
2263 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "pools"));
2264 TRY0(xmlTextWriterWriteFormatString(writer, "%u", ctx->poolcnt));
2265 TRY0(xmlTextWriterEndElement(writer)); /* pools */
2266 summary->contextsize += ctx->poolcnt * sizeof(isc_mempool_t);
2267
2268 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "hiwater"));
2269 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2270 (uint64_t)ctx->hi_water));
2271 TRY0(xmlTextWriterEndElement(writer)); /* hiwater */
2272
2273 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "lowater"));
2274 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2275 (uint64_t)ctx->lo_water));
2276 TRY0(xmlTextWriterEndElement(writer)); /* lowater */
2277
2278 TRY0(xmlTextWriterEndElement(writer)); /* context */
2279
2280 error:
2281 MCTXUNLOCK(ctx);
2282
2283 return (xmlrc);
2284 }
2285
2286 int
2287 isc_mem_renderxml(void *writer0) {
2288 isc__mem_t *ctx;
2289 summarystat_t summary;
2290 uint64_t lost;
2291 int xmlrc;
2292 xmlTextWriterPtr writer = (xmlTextWriterPtr)writer0;
2293
2294 memset(&summary, 0, sizeof(summary));
2295
2296 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "contexts"));
2297
2298 LOCK(&contextslock);
2299 lost = totallost;
2300 for (ctx = ISC_LIST_HEAD(contexts); ctx != NULL;
2301 ctx = ISC_LIST_NEXT(ctx, link)) {
2302 xmlrc = xml_renderctx(ctx, &summary, writer);
2303 if (xmlrc < 0) {
2304 UNLOCK(&contextslock);
2305 goto error;
2306 }
2307 }
2308 UNLOCK(&contextslock);
2309
2310 TRY0(xmlTextWriterEndElement(writer)); /* contexts */
2311
2312 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "summary"));
2313
2314 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "TotalUse"));
2315 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2316 summary.total));
2317 TRY0(xmlTextWriterEndElement(writer)); /* TotalUse */
2318
2319 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "InUse"));
2320 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2321 summary.inuse));
2322 TRY0(xmlTextWriterEndElement(writer)); /* InUse */
2323
2324 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "Malloced"));
2325 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2326 summary.malloced));
2327 TRY0(xmlTextWriterEndElement(writer)); /* InUse */
2328
2329 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "BlockSize"));
2330 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2331 summary.blocksize));
2332 TRY0(xmlTextWriterEndElement(writer)); /* BlockSize */
2333
2334 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "ContextSize"));
2335 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "",
2336 summary.contextsize));
2337 TRY0(xmlTextWriterEndElement(writer)); /* ContextSize */
2338
2339 TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "Lost"));
2340 TRY0(xmlTextWriterWriteFormatString(writer, "%" PRIu64 "", lost));
2341 TRY0(xmlTextWriterEndElement(writer)); /* Lost */
2342
2343 TRY0(xmlTextWriterEndElement(writer)); /* summary */
2344 error:
2345 return (xmlrc);
2346 }
2347
2348 #endif /* HAVE_LIBXML2 */
2349
2350 #ifdef HAVE_JSON_C
2351 #define CHECKMEM(m) RUNTIME_CHECK(m != NULL)
2352
2353 static isc_result_t
2354 json_renderctx(isc__mem_t *ctx, summarystat_t *summary, json_object *array) {
2355 REQUIRE(VALID_CONTEXT(ctx));
2356 REQUIRE(summary != NULL);
2357 REQUIRE(array != NULL);
2358
2359 json_object *ctxobj, *obj;
2360 char buf[1024];
2361
2362 MCTXLOCK(ctx);
2363
2364 summary->contextsize += sizeof(*ctx) +
2365 (ctx->max_size + 1) * sizeof(struct stats) +
2366 ctx->max_size * sizeof(element *) +
2367 ctx->basic_table_count * sizeof(char *);
2368 summary->total += ctx->total;
2369 summary->inuse += ctx->inuse;
2370 summary->malloced += ctx->malloced;
2371 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
2372 summary->blocksize += ctx->basic_table_count *
2373 NUM_BASIC_BLOCKS * ctx->mem_target;
2374 }
2375 #if ISC_MEM_TRACKLINES
2376 if (ctx->debuglist != NULL) {
2377 summary->contextsize += DEBUG_TABLE_COUNT *
2378 sizeof(debuglist_t) +
2379 ctx->debuglistcnt * sizeof(debuglink_t);
2380 }
2381 #endif /* if ISC_MEM_TRACKLINES */
2382
2383 ctxobj = json_object_new_object();
2384 CHECKMEM(ctxobj);
2385
2386 snprintf(buf, sizeof(buf), "%p", ctx);
2387 obj = json_object_new_string(buf);
2388 CHECKMEM(obj);
2389 json_object_object_add(ctxobj, "id", obj);
2390
2391 if (ctx->name[0] != 0) {
2392 obj = json_object_new_string(ctx->name);
2393 CHECKMEM(obj);
2394 json_object_object_add(ctxobj, "name", obj);
2395 }
2396
2397 obj = json_object_new_int64(isc_refcount_current(&ctx->references));
2398 CHECKMEM(obj);
2399 json_object_object_add(ctxobj, "references", obj);
2400
2401 obj = json_object_new_int64(ctx->total);
2402 CHECKMEM(obj);
2403 json_object_object_add(ctxobj, "total", obj);
2404
2405 obj = json_object_new_int64(ctx->inuse);
2406 CHECKMEM(obj);
2407 json_object_object_add(ctxobj, "inuse", obj);
2408
2409 obj = json_object_new_int64(ctx->maxinuse);
2410 CHECKMEM(obj);
2411 json_object_object_add(ctxobj, "maxinuse", obj);
2412
2413 obj = json_object_new_int64(ctx->malloced);
2414 CHECKMEM(obj);
2415 json_object_object_add(ctxobj, "malloced", obj);
2416
2417 obj = json_object_new_int64(ctx->maxmalloced);
2418 CHECKMEM(obj);
2419 json_object_object_add(ctxobj, "maxmalloced", obj);
2420
2421 if ((ctx->flags & ISC_MEMFLAG_INTERNAL) != 0) {
2422 uint64_t blocksize;
2423 blocksize = ctx->basic_table_count * NUM_BASIC_BLOCKS *
2424 ctx->mem_target;
2425 obj = json_object_new_int64(blocksize);
2426 CHECKMEM(obj);
2427 json_object_object_add(ctxobj, "blocksize", obj);
2428 }
2429
2430 obj = json_object_new_int64(ctx->poolcnt);
2431 CHECKMEM(obj);
2432 json_object_object_add(ctxobj, "pools", obj);
2433
2434 summary->contextsize += ctx->poolcnt * sizeof(isc_mempool_t);
2435
2436 obj = json_object_new_int64(ctx->hi_water);
2437 CHECKMEM(obj);
2438 json_object_object_add(ctxobj, "hiwater", obj);
2439
2440 obj = json_object_new_int64(ctx->lo_water);
2441 CHECKMEM(obj);
2442 json_object_object_add(ctxobj, "lowater", obj);
2443
2444 MCTXUNLOCK(ctx);
2445 json_object_array_add(array, ctxobj);
2446 return (ISC_R_SUCCESS);
2447 }
2448
2449 isc_result_t
2450 isc_mem_renderjson(void *memobj0) {
2451 isc_result_t result = ISC_R_SUCCESS;
2452 isc__mem_t *ctx;
2453 summarystat_t summary;
2454 uint64_t lost;
2455 json_object *ctxarray, *obj;
2456 json_object *memobj = (json_object *)memobj0;
2457
2458 memset(&summary, 0, sizeof(summary));
2459
2460 ctxarray = json_object_new_array();
2461 CHECKMEM(ctxarray);
2462
2463 LOCK(&contextslock);
2464 lost = totallost;
2465 for (ctx = ISC_LIST_HEAD(contexts); ctx != NULL;
2466 ctx = ISC_LIST_NEXT(ctx, link)) {
2467 result = json_renderctx(ctx, &summary, ctxarray);
2468 if (result != ISC_R_SUCCESS) {
2469 UNLOCK(&contextslock);
2470 goto error;
2471 }
2472 }
2473 UNLOCK(&contextslock);
2474
2475 obj = json_object_new_int64(summary.total);
2476 CHECKMEM(obj);
2477 json_object_object_add(memobj, "TotalUse", obj);
2478
2479 obj = json_object_new_int64(summary.inuse);
2480 CHECKMEM(obj);
2481 json_object_object_add(memobj, "InUse", obj);
2482
2483 obj = json_object_new_int64(summary.malloced);
2484 CHECKMEM(obj);
2485 json_object_object_add(memobj, "Malloced", obj);
2486
2487 obj = json_object_new_int64(summary.blocksize);
2488 CHECKMEM(obj);
2489 json_object_object_add(memobj, "BlockSize", obj);
2490
2491 obj = json_object_new_int64(summary.contextsize);
2492 CHECKMEM(obj);
2493 json_object_object_add(memobj, "ContextSize", obj);
2494
2495 obj = json_object_new_int64(lost);
2496 CHECKMEM(obj);
2497 json_object_object_add(memobj, "Lost", obj);
2498
2499 json_object_object_add(memobj, "contexts", ctxarray);
2500 return (ISC_R_SUCCESS);
2501
2502 error:
2503 if (ctxarray != NULL) {
2504 json_object_put(ctxarray);
2505 }
2506 return (result);
2507 }
2508 #endif /* HAVE_JSON_C */
2509
2510 void
2511 isc_mem_create(isc_mem_t **mctxp) {
2512 mem_create(mctxp, isc_mem_defaultflags);
2513 }
2514
2515 void *
2516 isc__mem_get(isc_mem_t *mctx, size_t size FLARG) {
2517 REQUIRE(ISCAPI_MCTX_VALID(mctx));
2518
2519 return (mctx->methods->memget(mctx, size FLARG_PASS));
2520 }
2521
2522 void
2523 isc__mem_put(isc_mem_t *mctx, void *ptr, size_t size FLARG) {
2524 REQUIRE(ISCAPI_MCTX_VALID(mctx));
2525
2526 mctx->methods->memput(mctx, ptr, size FLARG_PASS);
2527 }
2528
2529 void
2530 isc__mem_putanddetach(isc_mem_t **mctxp, void *ptr, size_t size FLARG) {
2531 REQUIRE(mctxp != NULL && ISCAPI_MCTX_VALID(*mctxp));
2532
2533 (*mctxp)->methods->memputanddetach(mctxp, ptr, size FLARG_PASS);
2534 }
2535
2536 void *
2537 isc__mem_allocate(isc_mem_t *mctx, size_t size FLARG) {
2538 REQUIRE(ISCAPI_MCTX_VALID(mctx));
2539
2540 return (mctx->methods->memallocate(mctx, size FLARG_PASS));
2541 }
2542
2543 void *
2544 isc__mem_reallocate(isc_mem_t *mctx, void *ptr, size_t size FLARG) {
2545 REQUIRE(ISCAPI_MCTX_VALID(mctx));
2546
2547 return (mctx->methods->memreallocate(mctx, ptr, size FLARG_PASS));
2548 }
2549
2550 char *
2551 isc__mem_strdup(isc_mem_t *mctx, const char *s FLARG) {
2552 REQUIRE(ISCAPI_MCTX_VALID(mctx));
2553
2554 return (mctx->methods->memstrdup(mctx, s FLARG_PASS));
2555 }
2556
2557 void
2558 isc__mem_free(isc_mem_t *mctx, void *ptr FLARG) {
2559 REQUIRE(ISCAPI_MCTX_VALID(mctx));
2560
2561 mctx->methods->memfree(mctx, ptr FLARG_PASS);
2562 }
2563
2564 void
2565 isc__mem_printactive(isc_mem_t *ctx0, FILE *file) {
2566 #if ISC_MEM_TRACKLINES
2567 REQUIRE(VALID_CONTEXT(ctx0));
2568 REQUIRE(file != NULL);
2569
2570 isc__mem_t *ctx = (isc__mem_t *)ctx0;
2571
2572 print_active(ctx, file);
2573 #else /* if ISC_MEM_TRACKLINES */
2574 UNUSED(ctx0);
2575 UNUSED(file);
2576 #endif /* if ISC_MEM_TRACKLINES */
2577 }
2578