2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2012, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Memory Management
23 * \author Mark Spencer <markster@digium.com>
24 * \author Richard Mudgett <rmudgett@digium.com>
28 <support_level>core</support_level>
33 #if defined(__AST_DEBUG_MALLOC)
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37 #include "asterisk/paths.h" /* use ast_config_AST_LOG_DIR */
41 #include "asterisk/cli.h"
42 #include "asterisk/lock.h"
43 #include "asterisk/strings.h"
44 #include "asterisk/unaligned.h"
45 #include "asterisk/backtrace.h"
48 * The larger the number the faster memory can be freed.
49 * However, more memory then is used for the regions[] hash
52 #define SOME_PRIME 1567
64 /* Undefine all our macros */
74 #define FENCE_MAGIC 0xfeedbabe /*!< Allocated memory high/low fence overwrite check. */
75 #define FREED_MAGIC 0xdeaddead /*!< Freed memory wipe filler. */
76 #define MALLOC_FILLER 0x55 /*!< Malloced memory filler. Must not be zero. */
81 AST_LIST_ENTRY(ast_region) node;
84 unsigned int cache; /* region was allocated as part of a cache pool */
90 * \brief Lower guard fence.
92 * \note Must be right before data[].
94 * \note Padding between fence and data[] is irrelevent because
95 * data[] is used to fill in the lower fence check value and not
96 * the fence member. The fence member is to ensure that there
97 * is space reserved for the fence check value.
101 * \brief Location of the requested malloc block to return.
103 * \note Must have the same alignment that malloc returns.
104 * i.e., It is suitably aligned for any kind of varible.
106 unsigned char data[0] __attribute__((aligned));
109 /*! Hash table of lists of active allocated memory regions. */
110 static struct ast_region *regions[SOME_PRIME];
112 /*! Number of freed regions to keep around to delay actually freeing them. */
113 #define FREED_MAX_COUNT 1500
115 /*! Maximum size of a minnow block */
116 #define MINNOWS_MAX_SIZE 50
118 struct ast_freed_regions {
119 /*! Memory regions that have been freed. */
120 struct ast_region *regions[FREED_MAX_COUNT];
121 /*! Next index into freed regions[] to use. */
125 /*! Large memory blocks that have been freed. */
126 static struct ast_freed_regions whales;
127 /*! Small memory blocks that have been freed. */
128 static struct ast_freed_regions minnows;
131 /*! No summary at exit. */
133 /*! Bit set if summary by line at exit. */
134 SUMMARY_BY_LINE = (1 << 0),
135 /*! Bit set if summary by function at exit. */
136 SUMMARY_BY_FUNC = (1 << 1),
137 /*! Bit set if summary by file at exit. */
138 SUMMARY_BY_FILE = (1 << 2),
141 /*! Summary options of unfreed regions at exit. */
142 static enum summary_opts atexit_summary;
143 /*! Nonzero if the unfreed regions are listed at exit. */
144 static int atexit_list;
145 /*! Nonzero if the memory allocation backtrace is enabled. */
146 static int backtrace_enabled;
148 #define HASH(a) (((unsigned long)(a)) % ARRAY_LEN(regions))
150 /*! Tracking this mutex will cause infinite recursion, as the mutex tracking
151 * code allocates memory */
152 AST_MUTEX_DEFINE_STATIC_NOTRACKING(reglock);
154 #define astmm_log(...) \
156 fprintf(stderr, __VA_ARGS__); \
158 fprintf(mmlog, __VA_ARGS__); \
163 void *ast_std_malloc(size_t size)
168 void *ast_std_calloc(size_t nmemb, size_t size)
170 return calloc(nmemb, size);
173 void *ast_std_realloc(void *ptr, size_t size)
175 return realloc(ptr, size);
178 void ast_std_free(void *ptr)
183 void ast_free_ptr(void *ptr)
188 static void print_backtrace(struct ast_bt *bt)
197 if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
198 astmm_log("Memory allocation backtrace:\n");
199 for (i = 3; i < bt->num_frames - 2; i++) {
200 astmm_log("#%d: [%p] %s\n", i - 3, bt->addresses[i], strings[i]);
202 ast_std_free(strings);
209 * \note If DO_CRASH is not defined then the function returns.
213 static void my_do_crash(void)
216 * Give the logger a chance to get the message out, just in case
217 * we abort(), or Asterisk crashes due to whatever problem just
224 static void *__ast_alloc_region(size_t size, const enum func_type which, const char *file, int lineno, const char *func, unsigned int cache)
226 struct ast_region *reg;
230 if (!(reg = malloc(size + sizeof(*reg) + sizeof(*fence)))) {
231 astmm_log("Memory Allocation Failure - '%d' bytes at %s %s() line %d\n",
232 (int) size, file, func, lineno);
238 reg->lineno = lineno;
240 reg->bt = backtrace_enabled ? ast_bt_create() : NULL;
241 ast_copy_string(reg->file, file, sizeof(reg->file));
242 ast_copy_string(reg->func, func, sizeof(reg->func));
247 * We use the bytes just preceeding reg->data and not reg->fence
248 * because there is likely to be padding between reg->fence and
249 * reg->data for reg->data alignment.
251 fence = (unsigned int *) (reg->data - sizeof(*fence));
252 *fence = FENCE_MAGIC;
254 /* Init higher fence. */
255 fence = (unsigned int *) (reg->data + reg->len);
256 put_unaligned_uint32(fence, FENCE_MAGIC);
258 hash = HASH(reg->data);
259 ast_mutex_lock(®lock);
260 AST_LIST_NEXT(reg, node) = regions[hash];
262 ast_mutex_unlock(®lock);
269 * \brief Wipe the region payload data with a known value.
271 * \param reg Region block to be wiped.
275 static void region_data_wipe(struct ast_region *reg)
281 * Wipe the lower fence, the payload, and whatever amount of the
282 * higher fence that falls into alignment with the payload.
284 end = reg->data + reg->len;
285 for (pos = ®->fence; (void *) pos <= end; ++pos) {
292 * \brief Check the region payload data for memory corruption.
294 * \param reg Region block to be checked.
298 static void region_data_check(struct ast_region *reg)
304 * Check the lower fence, the payload, and whatever amount of
305 * the higher fence that falls into alignment with the payload.
307 end = reg->data + reg->len;
308 for (pos = ®->fence; (void *) pos <= end; ++pos) {
309 if (*pos != FREED_MAGIC) {
310 astmm_log("WARNING: Memory corrupted after free of %p allocated at %s %s() line %d\n",
311 reg->data, reg->file, reg->func, reg->lineno);
312 print_backtrace(reg->bt);
321 * \brief Flush the circular array of freed regions.
323 * \param freed Already freed region blocks storage.
327 static void freed_regions_flush(struct ast_freed_regions *freed)
330 struct ast_region *old;
332 ast_mutex_lock(®lock);
333 for (idx = 0; idx < ARRAY_LEN(freed->regions); ++idx) {
334 old = freed->regions[idx];
335 freed->regions[idx] = NULL;
337 region_data_check(old);
342 ast_mutex_unlock(®lock);
347 * \brief Delay freeing a region block.
349 * \param freed Already freed region blocks storage.
350 * \param reg Region block to be freed.
354 static void region_free(struct ast_freed_regions *freed, struct ast_region *reg)
356 struct ast_region *old;
358 region_data_wipe(reg);
360 ast_mutex_lock(®lock);
361 old = freed->regions[freed->index];
362 freed->regions[freed->index] = reg;
365 if (ARRAY_LEN(freed->regions) <= freed->index) {
368 ast_mutex_unlock(®lock);
371 region_data_check(old);
372 old->bt = ast_bt_destroy(old->bt);
379 * \brief Remove a region from the active regions.
381 * \param ptr Region payload data pointer.
383 * \retval region on success.
384 * \retval NULL if not found.
386 static struct ast_region *region_remove(void *ptr)
389 struct ast_region *reg;
390 struct ast_region *prev = NULL;
394 ast_mutex_lock(®lock);
395 for (reg = regions[hash]; reg; reg = AST_LIST_NEXT(reg, node)) {
396 if (reg->data == ptr) {
398 AST_LIST_NEXT(prev, node) = AST_LIST_NEXT(reg, node);
400 regions[hash] = AST_LIST_NEXT(reg, node);
406 ast_mutex_unlock(®lock);
413 * \brief Check the fences of a region.
415 * \param reg Region block to check.
419 static void region_check_fences(struct ast_region *reg)
424 * We use the bytes just preceeding reg->data and not reg->fence
425 * because there is likely to be padding between reg->fence and
426 * reg->data for reg->data alignment.
428 fence = (unsigned int *) (reg->data - sizeof(*fence));
429 if (*fence != FENCE_MAGIC) {
430 astmm_log("WARNING: Low fence violation of %p allocated at %s %s() line %d\n",
431 reg->data, reg->file, reg->func, reg->lineno);
432 print_backtrace(reg->bt);
435 fence = (unsigned int *) (reg->data + reg->len);
436 if (get_unaligned_uint32(fence) != FENCE_MAGIC) {
437 astmm_log("WARNING: High fence violation of %p allocated at %s %s() line %d\n",
438 reg->data, reg->file, reg->func, reg->lineno);
439 print_backtrace(reg->bt);
446 * \brief Check the fences of all regions currently allocated.
450 static void regions_check_all_fences(void)
453 struct ast_region *reg;
455 ast_mutex_lock(®lock);
456 for (idx = 0; idx < ARRAY_LEN(regions); ++idx) {
457 for (reg = regions[idx]; reg; reg = AST_LIST_NEXT(reg, node)) {
458 region_check_fences(reg);
461 ast_mutex_unlock(®lock);
464 static void __ast_free_region(void *ptr, const char *file, int lineno, const char *func)
466 struct ast_region *reg;
472 reg = region_remove(ptr);
474 region_check_fences(reg);
476 if (reg->len <= MINNOWS_MAX_SIZE) {
477 region_free(&minnows, reg);
479 region_free(&whales, reg);
483 * This memory region is not registered. It could be because of
484 * a double free or the memory block was not allocated by the
487 astmm_log("WARNING: Freeing unregistered memory %p by %s %s() line %d\n",
488 ptr, file, func, lineno);
493 void *__ast_calloc(size_t nmemb, size_t size, const char *file, int lineno, const char *func)
497 ptr = __ast_alloc_region(size * nmemb, FUNC_CALLOC, file, lineno, func, 0);
499 memset(ptr, 0, size * nmemb);
505 void *__ast_calloc_cache(size_t nmemb, size_t size, const char *file, int lineno, const char *func)
509 ptr = __ast_alloc_region(size * nmemb, FUNC_CALLOC, file, lineno, func, 1);
511 memset(ptr, 0, size * nmemb);
517 void *__ast_malloc(size_t size, const char *file, int lineno, const char *func)
521 ptr = __ast_alloc_region(size, FUNC_MALLOC, file, lineno, func, 0);
523 /* Make sure that the malloced memory is not zero. */
524 memset(ptr, MALLOC_FILLER, size);
530 void __ast_free(void *ptr, const char *file, int lineno, const char *func)
532 __ast_free_region(ptr, file, lineno, func);
536 * \note reglock must be locked before calling.
538 static struct ast_region *region_find(void *ptr)
541 struct ast_region *reg;
544 for (reg = regions[hash]; reg; reg = AST_LIST_NEXT(reg, node)) {
545 if (reg->data == ptr) {
553 void *__ast_realloc(void *ptr, size_t size, const char *file, int lineno, const char *func)
556 struct ast_region *found;
560 ast_mutex_lock(®lock);
561 found = region_find(ptr);
563 ast_mutex_unlock(®lock);
564 astmm_log("WARNING: Realloc of unregistered memory %p by %s %s() line %d\n",
565 ptr, file, func, lineno);
570 ast_mutex_unlock(®lock);
577 __ast_free_region(ptr, file, lineno, func);
581 new_mem = __ast_alloc_region(size, FUNC_REALLOC, file, lineno, func, 0);
584 /* Copy the old data to the new malloced memory. */
586 memcpy(new_mem, ptr, size);
588 memcpy(new_mem, ptr, len);
589 /* Make sure that the added memory is not zero. */
590 memset(new_mem + len, MALLOC_FILLER, size - len);
592 __ast_free_region(ptr, file, lineno, func);
594 /* Make sure that the malloced memory is not zero. */
595 memset(new_mem, MALLOC_FILLER, size);
602 char *__ast_strdup(const char *s, const char *file, int lineno, const char *func)
611 if ((ptr = __ast_alloc_region(len, FUNC_STRDUP, file, lineno, func, 0)))
617 char *__ast_strndup(const char *s, size_t n, const char *file, int lineno, const char *func)
627 if ((ptr = __ast_alloc_region(len + 1, FUNC_STRNDUP, file, lineno, func, 0))) {
635 int __ast_asprintf(const char *file, int lineno, const char *func, char **strp, const char *fmt, ...)
644 size = vsnprintf(&s, 1, fmt, ap2);
646 if (!(*strp = __ast_alloc_region(size + 1, FUNC_ASPRINTF, file, lineno, func, 0))) {
650 vsnprintf(*strp, size + 1, fmt, ap);
656 int __ast_vasprintf(char **strp, const char *fmt, va_list ap, const char *file, int lineno, const char *func)
664 size = vsnprintf(&s, 1, fmt, ap2);
666 if (!(*strp = __ast_alloc_region(size + 1, FUNC_VASPRINTF, file, lineno, func, 0))) {
670 vsnprintf(*strp, size + 1, fmt, ap);
675 static char *handle_memory_atexit_list(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
679 e->command = "memory atexit list";
681 "Usage: memory atexit list {on|off}\n"
682 " Enable dumping a list of still allocated memory segments at exit.\n";
686 const char * const options[] = { "off", "on", NULL };
688 return ast_cli_complete(a->word, options, a->n);
694 return CLI_SHOWUSAGE;
697 if (ast_true(a->argv[3])) {
699 } else if (ast_false(a->argv[3])) {
702 return CLI_SHOWUSAGE;
705 ast_cli(a->fd, "The atexit list is: %s\n", atexit_list ? "On" : "Off");
710 static char *handle_memory_atexit_summary(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
716 e->command = "memory atexit summary";
718 "Usage: memory atexit summary {off|byline|byfunc|byfile}\n"
719 " Summary of still allocated memory segments at exit options.\n"
720 " off - Disable at exit summary.\n"
721 " byline - Enable at exit summary by file line number.\n"
722 " byfunc - Enable at exit summary by function name.\n"
723 " byfile - Enable at exit summary by file.\n"
725 " Note: byline, byfunc, and byfile are cumulative enables.\n";
729 const char * const options[] = { "off", "byline", "byfunc", "byfile", NULL };
731 return ast_cli_complete(a->word, options, a->n);
737 return CLI_SHOWUSAGE;
740 if (ast_false(a->argv[3])) {
741 atexit_summary = SUMMARY_OFF;
742 } else if (!strcasecmp(a->argv[3], "byline")) {
743 atexit_summary |= SUMMARY_BY_LINE;
744 } else if (!strcasecmp(a->argv[3], "byfunc")) {
745 atexit_summary |= SUMMARY_BY_FUNC;
746 } else if (!strcasecmp(a->argv[3], "byfile")) {
747 atexit_summary |= SUMMARY_BY_FILE;
749 return CLI_SHOWUSAGE;
752 if (atexit_summary) {
754 if (atexit_summary & SUMMARY_BY_LINE) {
755 strcat(buf, "byline");
757 if (atexit_summary & SUMMARY_BY_FUNC) {
761 strcat(buf, "byfunc");
763 if (atexit_summary & SUMMARY_BY_FILE) {
767 strcat(buf, "byfile");
772 ast_cli(a->fd, "The atexit summary is: %s\n", buf);
777 static char *handle_memory_show_allocations(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
779 const char *fn = NULL;
780 struct ast_region *reg;
782 unsigned int len = 0;
783 unsigned int cache_len = 0;
784 unsigned int count = 0;
788 e->command = "memory show allocations";
790 "Usage: memory show allocations [<file>|anomalies]\n"
791 " Dumps a list of segments of allocated memory.\n"
792 " Defaults to listing all memory allocations.\n"
793 " <file> - Restricts output to memory allocated by the file.\n"
794 " anomalies - Only check for fence violations.\n";
802 } else if (a->argc != 3) {
803 return CLI_SHOWUSAGE;
806 /* Look for historical misspelled option as well. */
807 if (fn && (!strcasecmp(fn, "anomalies") || !strcasecmp(fn, "anomolies"))) {
808 regions_check_all_fences();
809 ast_cli(a->fd, "Anomaly check complete.\n");
813 ast_mutex_lock(®lock);
814 for (idx = 0; idx < ARRAY_LEN(regions); ++idx) {
815 for (reg = regions[idx]; reg; reg = AST_LIST_NEXT(reg, node)) {
816 if (fn && strcasecmp(fn, reg->file)) {
820 region_check_fences(reg);
822 ast_cli(a->fd, "%10u bytes allocated%s by %20s() line %5u of %s\n",
823 (unsigned int) reg->len, reg->cache ? " (cache)" : "",
824 reg->func, reg->lineno, reg->file);
828 cache_len += reg->len;
833 ast_mutex_unlock(®lock);
836 ast_cli(a->fd, "%u bytes allocated (%u in caches) in %u allocations\n",
837 len, cache_len, count);
839 ast_cli(a->fd, "%u bytes allocated in %u allocations\n", len, count);
845 static char *handle_memory_show_summary(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
847 #define my_max(a, b) ((a) >= (b) ? (a) : (b))
849 const char *fn = NULL;
852 struct ast_region *reg;
853 unsigned int len = 0;
854 unsigned int cache_len = 0;
855 unsigned int count = 0;
856 struct file_summary {
857 struct file_summary *next;
859 unsigned int cache_len;
862 char name[my_max(sizeof(reg->file), sizeof(reg->func))];
863 } *list = NULL, *cur, **prev;
867 e->command = "memory show summary";
869 "Usage: memory show summary [<file>]\n"
870 " Summarizes heap memory allocations by file, or optionally\n"
871 " by line, if a file is specified.\n";
879 } else if (a->argc != 3) {
880 return CLI_SHOWUSAGE;
883 ast_mutex_lock(®lock);
884 for (idx = 0; idx < ARRAY_LEN(regions); ++idx) {
885 for (reg = regions[idx]; reg; reg = AST_LIST_NEXT(reg, node)) {
887 if (strcasecmp(fn, reg->file)) {
891 /* Sort list by func/lineno. Find existing or place to insert. */
892 for (prev = &list; (cur = *prev); prev = &cur->next) {
893 cmp = strcmp(cur->name, reg->func);
898 /* Insert before current */
902 cmp = cur->lineno - reg->lineno;
907 /* Insert before current */
913 /* Sort list by filename. Find existing or place to insert. */
914 for (prev = &list; (cur = *prev); prev = &cur->next) {
915 cmp = strcmp(cur->name, reg->file);
920 /* Insert before current */
928 cur = ast_alloca(sizeof(*cur));
929 memset(cur, 0, sizeof(*cur));
930 cur->lineno = reg->lineno;
931 ast_copy_string(cur->name, fn ? reg->func : reg->file, sizeof(cur->name));
937 cur->len += reg->len;
939 cur->cache_len += reg->len;
944 ast_mutex_unlock(®lock);
946 /* Dump the whole list */
947 for (cur = list; cur; cur = cur->next) {
949 cache_len += cur->cache_len;
951 if (cur->cache_len) {
953 ast_cli(a->fd, "%10u bytes (%10u cache) in %10u allocations by %20s() line %5u of %s\n",
954 cur->len, cur->cache_len, cur->count, cur->name, cur->lineno, fn);
956 ast_cli(a->fd, "%10u bytes (%10u cache) in %10u allocations in file %s\n",
957 cur->len, cur->cache_len, cur->count, cur->name);
961 ast_cli(a->fd, "%10u bytes in %10u allocations by %20s() line %5u of %s\n",
962 cur->len, cur->count, cur->name, cur->lineno, fn);
964 ast_cli(a->fd, "%10u bytes in %10u allocations in file %s\n",
965 cur->len, cur->count, cur->name);
971 ast_cli(a->fd, "%u bytes allocated (%u in caches) in %u allocations\n",
972 len, cache_len, count);
974 ast_cli(a->fd, "%u bytes allocated in %u allocations\n", len, count);
980 static char *handle_memory_backtrace(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
984 e->command = "memory backtrace";
986 "Usage: memory backtrace {on|off}\n"
987 " Enable dumping an allocation backtrace with memory diagnostics.\n"
988 " Note that saving the backtrace data for each allocation\n"
989 " can be CPU intensive.\n";
993 const char * const options[] = { "off", "on", NULL };
995 return ast_cli_complete(a->word, options, a->n);
1001 return CLI_SHOWUSAGE;
1004 if (ast_true(a->argv[2])) {
1005 backtrace_enabled = 1;
1006 } else if (ast_false(a->argv[2])) {
1007 backtrace_enabled = 0;
1009 return CLI_SHOWUSAGE;
1012 ast_cli(a->fd, "The memory backtrace is: %s\n", backtrace_enabled ? "On" : "Off");
1017 static struct ast_cli_entry cli_memory[] = {
1018 AST_CLI_DEFINE(handle_memory_atexit_list, "Enable memory allocations not freed at exit list."),
1019 AST_CLI_DEFINE(handle_memory_atexit_summary, "Enable memory allocations not freed at exit summary."),
1020 AST_CLI_DEFINE(handle_memory_show_allocations, "Display outstanding memory allocations"),
1021 AST_CLI_DEFINE(handle_memory_show_summary, "Summarize outstanding memory allocations"),
1022 AST_CLI_DEFINE(handle_memory_backtrace, "Enable dumping an allocation backtrace with memory diagnostics."),
1025 AST_LIST_HEAD_NOLOCK(region_list, ast_region);
1029 * \brief Convert the allocated regions hash table to a list.
1031 * \param list Fill list with the allocated regions.
1034 * Take all allocated regions from the regions[] and put them
1037 * \note reglock must be locked before calling.
1039 * \note This function is destructive to the regions[] lists.
1041 * \return Length of list created.
1043 static size_t mm_atexit_hash_list(struct region_list *list)
1045 struct ast_region *reg;
1046 size_t total_length;
1050 for (idx = 0; idx < ARRAY_LEN(regions); ++idx) {
1051 while ((reg = regions[idx])) {
1052 regions[idx] = AST_LIST_NEXT(reg, node);
1053 AST_LIST_NEXT(reg, node) = NULL;
1054 AST_LIST_INSERT_HEAD(list, reg, node);
1058 return total_length;
1063 * \brief Put the regions list into the allocated regions hash table.
1065 * \param list List to put into the allocated regions hash table.
1067 * \note reglock must be locked before calling.
1071 static void mm_atexit_hash_restore(struct region_list *list)
1073 struct ast_region *reg;
1076 while ((reg = AST_LIST_REMOVE_HEAD(list, node))) {
1077 hash = HASH(reg->data);
1078 AST_LIST_NEXT(reg, node) = regions[hash];
1079 regions[hash] = reg;
1085 * \brief Sort regions comparision.
1087 * \param left Region to compare.
1088 * \param right Region to compare.
1090 * \retval <0 if left < right
1091 * \retval =0 if left == right
1092 * \retval >0 if left > right
1094 static int mm_atexit_cmp(struct ast_region *left, struct ast_region *right)
1100 /* Sort by filename. */
1101 cmp = strcmp(left->file, right->file);
1106 /* Sort by line number. */
1107 cmp = left->lineno - right->lineno;
1112 /* Sort by allocated size. */
1113 cmp_size = left->len - right->len;
1121 /* Sort by allocated pointers just because. */
1122 cmp_ptr = left->data - right->data;
1135 * \brief Merge the given sorted sublists into sorted order onto the end of the list.
1137 * \param list Merge sublists onto this list.
1138 * \param sub1 First sublist to merge.
1139 * \param sub2 Second sublist to merge.
1143 static void mm_atexit_list_merge(struct region_list *list, struct region_list *sub1, struct region_list *sub2)
1145 struct ast_region *reg;
1148 if (AST_LIST_EMPTY(sub1)) {
1149 /* The remaining sublist goes onto the list. */
1150 AST_LIST_APPEND_LIST(list, sub2, node);
1153 if (AST_LIST_EMPTY(sub2)) {
1154 /* The remaining sublist goes onto the list. */
1155 AST_LIST_APPEND_LIST(list, sub1, node);
1159 if (mm_atexit_cmp(AST_LIST_FIRST(sub1), AST_LIST_FIRST(sub2)) <= 0) {
1160 reg = AST_LIST_REMOVE_HEAD(sub1, node);
1162 reg = AST_LIST_REMOVE_HEAD(sub2, node);
1164 AST_LIST_INSERT_TAIL(list, reg, node);
1170 * \brief Take sublists off of the given list.
1172 * \param list Source list to remove sublists from the beginning of list.
1173 * \param sub Array of sublists to fill. (Lists are empty on entry.)
1174 * \param num_lists Number of lists to remove from the source list.
1175 * \param size Size of the sublists to remove.
1176 * \param remaining Remaining number of elements on the source list.
1180 static void mm_atexit_list_split(struct region_list *list, struct region_list sub[], size_t num_lists, size_t size, size_t *remaining)
1184 for (idx = 0; idx < num_lists; ++idx) {
1187 if (*remaining < size) {
1188 /* The remaining source list goes onto the sublist. */
1189 AST_LIST_APPEND_LIST(&sub[idx], list, node);
1194 /* Take a sublist off the beginning of the source list. */
1196 for (count = size; count--;) {
1197 struct ast_region *reg;
1199 reg = AST_LIST_REMOVE_HEAD(list, node);
1200 AST_LIST_INSERT_TAIL(&sub[idx], reg, node);
1207 * \brief Sort the regions list using mergesort.
1209 * \param list Allocated regions list to sort.
1210 * \param length Length of the list.
1214 static void mm_atexit_list_sort(struct region_list *list, size_t length)
1216 /*! Semi-sorted merged list. */
1217 struct region_list merged = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
1218 /*! Sublists to merge. (Can only merge two sublists at this time.) */
1219 struct region_list sub[2] = {
1220 AST_LIST_HEAD_NOLOCK_INIT_VALUE,
1221 AST_LIST_HEAD_NOLOCK_INIT_VALUE
1223 /*! Sublist size. */
1225 /*! Remaining elements in the list. */
1227 /*! Number of sublist merge passes to process the list. */
1234 while (!AST_LIST_EMPTY(list)) {
1235 mm_atexit_list_split(list, sub, ARRAY_LEN(sub), size, &remaining);
1236 mm_atexit_list_merge(&merged, &sub[0], &sub[1]);
1239 AST_LIST_APPEND_LIST(list, &merged, node);
1241 /* The list is now sorted. */
1245 /* Double the sublist size to remove for next round. */
1252 * \brief List all regions currently allocated.
1254 * \param alloced regions list.
1258 static void mm_atexit_regions_list(struct region_list *alloced)
1260 struct ast_region *reg;
1262 AST_LIST_TRAVERSE(alloced, reg, node) {
1263 astmm_log("%s %s() line %u: %u bytes%s at %p\n",
1264 reg->file, reg->func, reg->lineno,
1265 (unsigned int) reg->len, reg->cache ? " (cache)" : "", reg->data);
1271 * \brief Summarize all regions currently allocated.
1273 * \param alloced Sorted regions list.
1277 static void mm_atexit_regions_summary(struct region_list *alloced)
1279 struct ast_region *reg;
1280 struct ast_region *next;
1284 unsigned int cache_len;
1285 } by_line, by_func, by_file, total;
1289 by_line.cache_len = 0;
1293 by_func.cache_len = 0;
1297 by_file.cache_len = 0;
1301 total.cache_len = 0;
1303 AST_LIST_TRAVERSE(alloced, reg, node) {
1304 next = AST_LIST_NEXT(reg, node);
1307 by_line.len += reg->len;
1309 by_line.cache_len += reg->len;
1311 if (next && !strcmp(reg->file, next->file) && reg->lineno == next->lineno) {
1314 if (atexit_summary & SUMMARY_BY_LINE) {
1315 if (by_line.cache_len) {
1316 astmm_log("%10u bytes (%u in caches) in %u allocations. %s %s() line %u\n",
1317 by_line.len, by_line.cache_len, by_line.count, reg->file, reg->func, reg->lineno);
1319 astmm_log("%10u bytes in %5u allocations. %s %s() line %u\n",
1320 by_line.len, by_line.count, reg->file, reg->func, reg->lineno);
1324 by_func.count += by_line.count;
1325 by_func.len += by_line.len;
1326 by_func.cache_len += by_line.cache_len;
1329 by_line.cache_len = 0;
1330 if (next && !strcmp(reg->file, next->file) && !strcmp(reg->func, next->func)) {
1333 if (atexit_summary & SUMMARY_BY_FUNC) {
1334 if (by_func.cache_len) {
1335 astmm_log("%10u bytes (%u in caches) in %u allocations. %s %s()\n",
1336 by_func.len, by_func.cache_len, by_func.count, reg->file, reg->func);
1338 astmm_log("%10u bytes in %5u allocations. %s %s()\n",
1339 by_func.len, by_func.count, reg->file, reg->func);
1343 by_file.count += by_func.count;
1344 by_file.len += by_func.len;
1345 by_file.cache_len += by_func.cache_len;
1348 by_func.cache_len = 0;
1349 if (next && !strcmp(reg->file, next->file)) {
1352 if (atexit_summary & SUMMARY_BY_FILE) {
1353 if (by_file.cache_len) {
1354 astmm_log("%10u bytes (%u in caches) in %u allocations. %s\n",
1355 by_file.len, by_file.cache_len, by_file.count, reg->file);
1357 astmm_log("%10u bytes in %5u allocations. %s\n",
1358 by_file.len, by_file.count, reg->file);
1362 total.count += by_file.count;
1363 total.len += by_file.len;
1364 total.cache_len += by_file.cache_len;
1367 by_file.cache_len = 0;
1370 if (total.cache_len) {
1371 astmm_log("%u bytes (%u in caches) in %u allocations.\n",
1372 total.len, total.cache_len, total.count);
1374 astmm_log("%u bytes in %u allocations.\n", total.len, total.count);
1380 * \brief Dump the memory allocations atexit.
1382 * \note reglock must be locked before calling.
1386 static void mm_atexit_dump(void)
1388 struct region_list alloced_atexit = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
1391 length = mm_atexit_hash_list(&alloced_atexit);
1393 /* Wow! This is amazing! */
1394 astmm_log("Exiting with all memory freed.\n");
1398 mm_atexit_list_sort(&alloced_atexit, length);
1400 astmm_log("Exiting with the following memory not freed:\n");
1402 mm_atexit_regions_list(&alloced_atexit);
1404 if (atexit_summary) {
1405 mm_atexit_regions_summary(&alloced_atexit);
1409 * Put the alloced list back into regions[].
1411 * We have do do this because we can get called before all other
1412 * threads have terminated.
1414 mm_atexit_hash_restore(&alloced_atexit);
1421 static void mm_atexit_final(void)
1425 /* Only wait if we want atexit allocation dumps. */
1426 if (atexit_list || atexit_summary) {
1427 fprintf(stderr, "Waiting 10 seconds to let other threads die.\n");
1431 regions_check_all_fences();
1433 /* Flush all delayed memory free circular arrays. */
1434 freed_regions_flush(&whales);
1435 freed_regions_flush(&minnows);
1437 /* Peform atexit allocation dumps. */
1438 if (atexit_list || atexit_summary) {
1439 ast_mutex_lock(®lock);
1441 ast_mutex_unlock(®lock);
1444 /* Close the log file. */
1453 * \brief Initialize malloc debug phase 1.
1455 * \note Must be called first thing in main().
1459 void __ast_mm_init_phase_1(void)
1461 atexit(mm_atexit_final);
1468 static void mm_atexit_ast(void)
1470 ast_cli_unregister_multiple(cli_memory, ARRAY_LEN(cli_memory));
1474 * \brief Initialize malloc debug phase 2.
1478 void __ast_mm_init_phase_2(void)
1480 char filename[PATH_MAX];
1482 ast_cli_register_multiple(cli_memory, ARRAY_LEN(cli_memory));
1484 snprintf(filename, sizeof(filename), "%s/mmlog", ast_config_AST_LOG_DIR);
1486 ast_verb(1, "Asterisk Malloc Debugger Started (see %s))\n", filename);
1488 mmlog = fopen(filename, "a+");
1490 fprintf(mmlog, "%ld - New session\n", (long) time(NULL));
1493 ast_log(LOG_ERROR, "Could not open malloc debug log file: %s\n", filename);
1496 ast_register_atexit(mm_atexit_ast);
1499 #endif /* defined(__AST_DEBUG_MALLOC) */