astmm.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2012, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  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.
  13. *
  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.
  17. */
  18. /*! \file
  19. *
  20. * \brief Memory Management
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. * \author Richard Mudgett <rmudgett@digium.com>
  24. */
  25. /*** MODULEINFO
  26. <support_level>core</support_level>
  27. ***/
  28. #include "asterisk.h"
  29. #if defined(__AST_DEBUG_MALLOC)
  30. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  31. #include "asterisk/paths.h" /* use ast_config_AST_LOG_DIR */
  32. #include <stddef.h>
  33. #include <time.h>
  34. #include "asterisk/cli.h"
  35. #include "asterisk/lock.h"
  36. #include "asterisk/strings.h"
  37. #include "asterisk/unaligned.h"
  38. #include "asterisk/backtrace.h"
  39. /*!
  40. * The larger the number the faster memory can be freed.
  41. * However, more memory then is used for the regions[] hash
  42. * table.
  43. */
  44. #define SOME_PRIME 1567
  45. enum func_type {
  46. FUNC_CALLOC = 1,
  47. FUNC_MALLOC,
  48. FUNC_REALLOC,
  49. FUNC_STRDUP,
  50. FUNC_STRNDUP,
  51. FUNC_VASPRINTF,
  52. FUNC_ASPRINTF
  53. };
  54. /* Undefine all our macros */
  55. #undef malloc
  56. #undef calloc
  57. #undef realloc
  58. #undef strdup
  59. #undef strndup
  60. #undef free
  61. #undef vasprintf
  62. #undef asprintf
  63. #define FENCE_MAGIC 0xfeedbabe /*!< Allocated memory high/low fence overwrite check. */
  64. #define FREED_MAGIC 0xdeaddead /*!< Freed memory wipe filler. */
  65. #define MALLOC_FILLER 0x55 /*!< Malloced memory filler. Must not be zero. */
  66. static FILE *mmlog;
  67. struct ast_region {
  68. AST_LIST_ENTRY(ast_region) node;
  69. struct ast_bt *bt;
  70. size_t len;
  71. unsigned int cache; /* region was allocated as part of a cache pool */
  72. unsigned int lineno;
  73. enum func_type which;
  74. char file[64];
  75. char func[40];
  76. /*!
  77. * \brief Lower guard fence.
  78. *
  79. * \note Must be right before data[].
  80. *
  81. * \note Padding between fence and data[] is irrelevent because
  82. * data[] is used to fill in the lower fence check value and not
  83. * the fence member. The fence member is to ensure that there
  84. * is space reserved for the fence check value.
  85. */
  86. unsigned int fence;
  87. /*!
  88. * \brief Location of the requested malloc block to return.
  89. *
  90. * \note Must have the same alignment that malloc returns.
  91. * i.e., It is suitably aligned for any kind of varible.
  92. */
  93. unsigned char data[0] __attribute__((aligned));
  94. };
  95. /*! Hash table of lists of active allocated memory regions. */
  96. static struct ast_region *regions[SOME_PRIME];
  97. /*! Number of freed regions to keep around to delay actually freeing them. */
  98. #define FREED_MAX_COUNT 1500
  99. /*! Maximum size of a minnow block */
  100. #define MINNOWS_MAX_SIZE 50
  101. struct ast_freed_regions {
  102. /*! Memory regions that have been freed. */
  103. struct ast_region *regions[FREED_MAX_COUNT];
  104. /*! Next index into freed regions[] to use. */
  105. int index;
  106. };
  107. /*! Large memory blocks that have been freed. */
  108. static struct ast_freed_regions whales;
  109. /*! Small memory blocks that have been freed. */
  110. static struct ast_freed_regions minnows;
  111. enum summary_opts {
  112. /*! No summary at exit. */
  113. SUMMARY_OFF,
  114. /*! Bit set if summary by line at exit. */
  115. SUMMARY_BY_LINE = (1 << 0),
  116. /*! Bit set if summary by function at exit. */
  117. SUMMARY_BY_FUNC = (1 << 1),
  118. /*! Bit set if summary by file at exit. */
  119. SUMMARY_BY_FILE = (1 << 2),
  120. };
  121. /*! Summary options of unfreed regions at exit. */
  122. static enum summary_opts atexit_summary;
  123. /*! Nonzero if the unfreed regions are listed at exit. */
  124. static int atexit_list;
  125. /*! Nonzero if the memory allocation backtrace is enabled. */
  126. static int backtrace_enabled;
  127. #define HASH(a) (((unsigned long)(a)) % ARRAY_LEN(regions))
  128. /*! Tracking this mutex will cause infinite recursion, as the mutex tracking
  129. * code allocates memory */
  130. AST_MUTEX_DEFINE_STATIC_NOTRACKING(reglock);
  131. #define astmm_log(...) \
  132. do { \
  133. fprintf(stderr, __VA_ARGS__); \
  134. if (mmlog) { \
  135. fprintf(mmlog, __VA_ARGS__); \
  136. fflush(mmlog); \
  137. } \
  138. } while (0)
  139. void *ast_std_malloc(size_t size)
  140. {
  141. return malloc(size);
  142. }
  143. void *ast_std_calloc(size_t nmemb, size_t size)
  144. {
  145. return calloc(nmemb, size);
  146. }
  147. void *ast_std_realloc(void *ptr, size_t size)
  148. {
  149. return realloc(ptr, size);
  150. }
  151. void ast_std_free(void *ptr)
  152. {
  153. free(ptr);
  154. }
  155. void ast_free_ptr(void *ptr)
  156. {
  157. ast_free(ptr);
  158. }
  159. static void print_backtrace(struct ast_bt *bt)
  160. {
  161. int i = 0;
  162. struct ast_vector_string *strings;
  163. if (!bt) {
  164. return;
  165. }
  166. if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
  167. astmm_log("Memory allocation backtrace:\n");
  168. for (i = 3; i < AST_VECTOR_SIZE(strings) - 2; i++) {
  169. astmm_log("#%d: %s\n", i - 3, AST_VECTOR_GET(strings, i));
  170. }
  171. ast_bt_free_symbols(strings);
  172. }
  173. }
  174. /*!
  175. * \internal
  176. *
  177. * \note If DO_CRASH is not defined then the function returns.
  178. *
  179. * \return Nothing
  180. */
  181. static void my_do_crash(void)
  182. {
  183. /*
  184. * Give the logger a chance to get the message out, just in case
  185. * we abort(), or Asterisk crashes due to whatever problem just
  186. * happened.
  187. */
  188. usleep(1);
  189. ast_do_crash();
  190. }
  191. static void *__ast_alloc_region(size_t size, const enum func_type which, const char *file, int lineno, const char *func, unsigned int cache)
  192. {
  193. struct ast_region *reg;
  194. unsigned int *fence;
  195. int hash;
  196. DEBUG_CHAOS_RETURN(DEBUG_CHAOS_ALLOC_CHANCE, NULL);
  197. if (!(reg = malloc(size + sizeof(*reg) + sizeof(*fence)))) {
  198. astmm_log("Memory Allocation Failure - '%d' bytes at %s %s() line %d\n",
  199. (int) size, file, func, lineno);
  200. return NULL;
  201. }
  202. reg->len = size;
  203. reg->cache = cache;
  204. reg->lineno = lineno;
  205. reg->which = which;
  206. reg->bt = backtrace_enabled ? ast_bt_create() : NULL;
  207. ast_copy_string(reg->file, file, sizeof(reg->file));
  208. ast_copy_string(reg->func, func, sizeof(reg->func));
  209. /*
  210. * Init lower fence.
  211. *
  212. * We use the bytes just preceeding reg->data and not reg->fence
  213. * because there is likely to be padding between reg->fence and
  214. * reg->data for reg->data alignment.
  215. */
  216. fence = (unsigned int *) (reg->data - sizeof(*fence));
  217. *fence = FENCE_MAGIC;
  218. /* Init higher fence. */
  219. fence = (unsigned int *) (reg->data + reg->len);
  220. put_unaligned_uint32(fence, FENCE_MAGIC);
  221. hash = HASH(reg->data);
  222. ast_mutex_lock(&reglock);
  223. AST_LIST_NEXT(reg, node) = regions[hash];
  224. regions[hash] = reg;
  225. ast_mutex_unlock(&reglock);
  226. return reg->data;
  227. }
  228. /*!
  229. * \internal
  230. * \brief Wipe the region payload data with a known value.
  231. *
  232. * \param reg Region block to be wiped.
  233. *
  234. * \return Nothing
  235. */
  236. static void region_data_wipe(struct ast_region *reg)
  237. {
  238. void *end;
  239. unsigned int *pos;
  240. /*
  241. * Wipe the lower fence, the payload, and whatever amount of the
  242. * higher fence that falls into alignment with the payload.
  243. */
  244. end = reg->data + reg->len;
  245. for (pos = &reg->fence; (void *) pos <= end; ++pos) {
  246. *pos = FREED_MAGIC;
  247. }
  248. }
  249. /*!
  250. * \internal
  251. * \brief Check the region payload data for memory corruption.
  252. *
  253. * \param reg Region block to be checked.
  254. *
  255. * \return Nothing
  256. */
  257. static void region_data_check(struct ast_region *reg)
  258. {
  259. void *end;
  260. unsigned int *pos;
  261. /*
  262. * Check the lower fence, the payload, and whatever amount of
  263. * the higher fence that falls into alignment with the payload.
  264. */
  265. end = reg->data + reg->len;
  266. for (pos = &reg->fence; (void *) pos <= end; ++pos) {
  267. if (*pos != FREED_MAGIC) {
  268. astmm_log("WARNING: Memory corrupted after free of %p allocated at %s %s() line %d\n",
  269. reg->data, reg->file, reg->func, reg->lineno);
  270. print_backtrace(reg->bt);
  271. my_do_crash();
  272. break;
  273. }
  274. }
  275. }
  276. /*!
  277. * \internal
  278. * \brief Flush the circular array of freed regions.
  279. *
  280. * \param freed Already freed region blocks storage.
  281. *
  282. * \return Nothing
  283. */
  284. static void freed_regions_flush(struct ast_freed_regions *freed)
  285. {
  286. int idx;
  287. struct ast_region *old;
  288. ast_mutex_lock(&reglock);
  289. for (idx = 0; idx < ARRAY_LEN(freed->regions); ++idx) {
  290. old = freed->regions[idx];
  291. freed->regions[idx] = NULL;
  292. if (old) {
  293. region_data_check(old);
  294. free(old);
  295. }
  296. }
  297. freed->index = 0;
  298. ast_mutex_unlock(&reglock);
  299. }
  300. /*!
  301. * \internal
  302. * \brief Delay freeing a region block.
  303. *
  304. * \param freed Already freed region blocks storage.
  305. * \param reg Region block to be freed.
  306. *
  307. * \return Nothing
  308. */
  309. static void region_free(struct ast_freed_regions *freed, struct ast_region *reg)
  310. {
  311. struct ast_region *old;
  312. region_data_wipe(reg);
  313. ast_mutex_lock(&reglock);
  314. old = freed->regions[freed->index];
  315. freed->regions[freed->index] = reg;
  316. ++freed->index;
  317. if (ARRAY_LEN(freed->regions) <= freed->index) {
  318. freed->index = 0;
  319. }
  320. ast_mutex_unlock(&reglock);
  321. if (old) {
  322. region_data_check(old);
  323. old->bt = ast_bt_destroy(old->bt);
  324. free(old);
  325. }
  326. }
  327. /*!
  328. * \internal
  329. * \brief Remove a region from the active regions.
  330. *
  331. * \param ptr Region payload data pointer.
  332. *
  333. * \retval region on success.
  334. * \retval NULL if not found.
  335. */
  336. static struct ast_region *region_remove(void *ptr)
  337. {
  338. int hash;
  339. struct ast_region *reg;
  340. struct ast_region *prev = NULL;
  341. hash = HASH(ptr);
  342. ast_mutex_lock(&reglock);
  343. for (reg = regions[hash]; reg; reg = AST_LIST_NEXT(reg, node)) {
  344. if (reg->data == ptr) {
  345. if (prev) {
  346. AST_LIST_NEXT(prev, node) = AST_LIST_NEXT(reg, node);
  347. } else {
  348. regions[hash] = AST_LIST_NEXT(reg, node);
  349. }
  350. break;
  351. }
  352. prev = reg;
  353. }
  354. ast_mutex_unlock(&reglock);
  355. return reg;
  356. }
  357. /*!
  358. * \internal
  359. * \brief Check the fences of a region.
  360. *
  361. * \param reg Region block to check.
  362. *
  363. * \return Nothing
  364. */
  365. static void region_check_fences(struct ast_region *reg)
  366. {
  367. unsigned int *fence;
  368. /*
  369. * We use the bytes just preceeding reg->data and not reg->fence
  370. * because there is likely to be padding between reg->fence and
  371. * reg->data for reg->data alignment.
  372. */
  373. fence = (unsigned int *) (reg->data - sizeof(*fence));
  374. if (*fence != FENCE_MAGIC) {
  375. astmm_log("WARNING: Low fence violation of %p allocated at %s %s() line %d\n",
  376. reg->data, reg->file, reg->func, reg->lineno);
  377. print_backtrace(reg->bt);
  378. my_do_crash();
  379. }
  380. fence = (unsigned int *) (reg->data + reg->len);
  381. if (get_unaligned_uint32(fence) != FENCE_MAGIC) {
  382. astmm_log("WARNING: High fence violation of %p allocated at %s %s() line %d\n",
  383. reg->data, reg->file, reg->func, reg->lineno);
  384. print_backtrace(reg->bt);
  385. my_do_crash();
  386. }
  387. }
  388. /*!
  389. * \internal
  390. * \brief Check the fences of all regions currently allocated.
  391. *
  392. * \return Nothing
  393. */
  394. static void regions_check_all_fences(void)
  395. {
  396. int idx;
  397. struct ast_region *reg;
  398. ast_mutex_lock(&reglock);
  399. for (idx = 0; idx < ARRAY_LEN(regions); ++idx) {
  400. for (reg = regions[idx]; reg; reg = AST_LIST_NEXT(reg, node)) {
  401. region_check_fences(reg);
  402. }
  403. }
  404. ast_mutex_unlock(&reglock);
  405. }
  406. static void __ast_free_region(void *ptr, const char *file, int lineno, const char *func)
  407. {
  408. struct ast_region *reg;
  409. if (!ptr) {
  410. return;
  411. }
  412. reg = region_remove(ptr);
  413. if (reg) {
  414. region_check_fences(reg);
  415. if (reg->len <= MINNOWS_MAX_SIZE) {
  416. region_free(&minnows, reg);
  417. } else {
  418. region_free(&whales, reg);
  419. }
  420. } else {
  421. /*
  422. * This memory region is not registered. It could be because of
  423. * a double free or the memory block was not allocated by the
  424. * malloc debug code.
  425. */
  426. astmm_log("WARNING: Freeing unregistered memory %p by %s %s() line %d\n",
  427. ptr, file, func, lineno);
  428. my_do_crash();
  429. }
  430. }
  431. void *__ast_calloc(size_t nmemb, size_t size, const char *file, int lineno, const char *func)
  432. {
  433. void *ptr;
  434. ptr = __ast_alloc_region(size * nmemb, FUNC_CALLOC, file, lineno, func, 0);
  435. if (ptr) {
  436. memset(ptr, 0, size * nmemb);
  437. }
  438. return ptr;
  439. }
  440. void *__ast_calloc_cache(size_t nmemb, size_t size, const char *file, int lineno, const char *func)
  441. {
  442. void *ptr;
  443. ptr = __ast_alloc_region(size * nmemb, FUNC_CALLOC, file, lineno, func, 1);
  444. if (ptr) {
  445. memset(ptr, 0, size * nmemb);
  446. }
  447. return ptr;
  448. }
  449. void *__ast_malloc(size_t size, const char *file, int lineno, const char *func)
  450. {
  451. void *ptr;
  452. ptr = __ast_alloc_region(size, FUNC_MALLOC, file, lineno, func, 0);
  453. if (ptr) {
  454. /* Make sure that the malloced memory is not zero. */
  455. memset(ptr, MALLOC_FILLER, size);
  456. }
  457. return ptr;
  458. }
  459. void __ast_free(void *ptr, const char *file, int lineno, const char *func)
  460. {
  461. __ast_free_region(ptr, file, lineno, func);
  462. }
  463. /*!
  464. * \note reglock must be locked before calling.
  465. */
  466. static struct ast_region *region_find(void *ptr)
  467. {
  468. int hash;
  469. struct ast_region *reg;
  470. hash = HASH(ptr);
  471. for (reg = regions[hash]; reg; reg = AST_LIST_NEXT(reg, node)) {
  472. if (reg->data == ptr) {
  473. break;
  474. }
  475. }
  476. return reg;
  477. }
  478. void *__ast_realloc(void *ptr, size_t size, const char *file, int lineno, const char *func)
  479. {
  480. size_t len;
  481. struct ast_region *found;
  482. void *new_mem;
  483. if (ptr) {
  484. ast_mutex_lock(&reglock);
  485. found = region_find(ptr);
  486. if (!found) {
  487. ast_mutex_unlock(&reglock);
  488. astmm_log("WARNING: Realloc of unregistered memory %p by %s %s() line %d\n",
  489. ptr, file, func, lineno);
  490. my_do_crash();
  491. return NULL;
  492. }
  493. len = found->len;
  494. ast_mutex_unlock(&reglock);
  495. } else {
  496. found = NULL;
  497. len = 0;
  498. }
  499. if (!size) {
  500. __ast_free_region(ptr, file, lineno, func);
  501. return NULL;
  502. }
  503. new_mem = __ast_alloc_region(size, FUNC_REALLOC, file, lineno, func, 0);
  504. if (new_mem) {
  505. if (found) {
  506. /* Copy the old data to the new malloced memory. */
  507. if (size <= len) {
  508. memcpy(new_mem, ptr, size);
  509. } else {
  510. memcpy(new_mem, ptr, len);
  511. /* Make sure that the added memory is not zero. */
  512. memset(new_mem + len, MALLOC_FILLER, size - len);
  513. }
  514. __ast_free_region(ptr, file, lineno, func);
  515. } else {
  516. /* Make sure that the malloced memory is not zero. */
  517. memset(new_mem, MALLOC_FILLER, size);
  518. }
  519. }
  520. return new_mem;
  521. }
  522. char *__ast_strdup(const char *s, const char *file, int lineno, const char *func)
  523. {
  524. size_t len;
  525. void *ptr;
  526. if (!s)
  527. return NULL;
  528. len = strlen(s) + 1;
  529. if ((ptr = __ast_alloc_region(len, FUNC_STRDUP, file, lineno, func, 0)))
  530. strcpy(ptr, s);
  531. return ptr;
  532. }
  533. char *__ast_strndup(const char *s, size_t n, const char *file, int lineno, const char *func)
  534. {
  535. size_t len;
  536. char *ptr;
  537. if (!s) {
  538. return NULL;
  539. }
  540. len = strnlen(s, n);
  541. if ((ptr = __ast_alloc_region(len + 1, FUNC_STRNDUP, file, lineno, func, 0))) {
  542. memcpy(ptr, s, len);
  543. ptr[len] = '\0';
  544. }
  545. return ptr;
  546. }
  547. int __ast_asprintf(const char *file, int lineno, const char *func, char **strp, const char *fmt, ...)
  548. {
  549. int size;
  550. va_list ap, ap2;
  551. char s;
  552. *strp = NULL;
  553. va_start(ap, fmt);
  554. va_copy(ap2, ap);
  555. size = vsnprintf(&s, 1, fmt, ap2);
  556. va_end(ap2);
  557. if (!(*strp = __ast_alloc_region(size + 1, FUNC_ASPRINTF, file, lineno, func, 0))) {
  558. va_end(ap);
  559. return -1;
  560. }
  561. vsnprintf(*strp, size + 1, fmt, ap);
  562. va_end(ap);
  563. return size;
  564. }
  565. int __ast_vasprintf(char **strp, const char *fmt, va_list ap, const char *file, int lineno, const char *func)
  566. {
  567. int size;
  568. va_list ap2;
  569. char s;
  570. *strp = NULL;
  571. va_copy(ap2, ap);
  572. size = vsnprintf(&s, 1, fmt, ap2);
  573. va_end(ap2);
  574. if (!(*strp = __ast_alloc_region(size + 1, FUNC_VASPRINTF, file, lineno, func, 0))) {
  575. return -1;
  576. }
  577. vsnprintf(*strp, size + 1, fmt, ap);
  578. return size;
  579. }
  580. /*!
  581. * \internal
  582. * \brief Count the number of bytes in the specified freed region.
  583. *
  584. * \param freed Already freed region blocks storage.
  585. *
  586. * \note reglock must be locked before calling.
  587. *
  588. * \return Number of bytes in freed region.
  589. */
  590. static size_t freed_regions_size(struct ast_freed_regions *freed)
  591. {
  592. size_t total_len = 0;
  593. int idx;
  594. struct ast_region *old;
  595. for (idx = 0; idx < ARRAY_LEN(freed->regions); ++idx) {
  596. old = freed->regions[idx];
  597. if (old) {
  598. total_len += old->len;
  599. }
  600. }
  601. return total_len;
  602. }
  603. static char *handle_memory_atexit_list(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  604. {
  605. switch (cmd) {
  606. case CLI_INIT:
  607. e->command = "memory atexit list {on|off}";
  608. e->usage =
  609. "Usage: memory atexit list {on|off}\n"
  610. " Enable dumping a list of still allocated memory segments at exit.\n";
  611. return NULL;
  612. case CLI_GENERATE:
  613. return NULL;
  614. }
  615. if (a->argc != 4) {
  616. return CLI_SHOWUSAGE;
  617. }
  618. if (ast_true(a->argv[3])) {
  619. atexit_list = 1;
  620. } else if (ast_false(a->argv[3])) {
  621. atexit_list = 0;
  622. } else {
  623. return CLI_SHOWUSAGE;
  624. }
  625. ast_cli(a->fd, "The atexit list is: %s\n", atexit_list ? "On" : "Off");
  626. return CLI_SUCCESS;
  627. }
  628. static char *handle_memory_atexit_summary(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  629. {
  630. char buf[80];
  631. switch (cmd) {
  632. case CLI_INIT:
  633. e->command = "memory atexit summary {off|byline|byfunc|byfile}";
  634. e->usage =
  635. "Usage: memory atexit summary {off|byline|byfunc|byfile}\n"
  636. " Summary of still allocated memory segments at exit options.\n"
  637. " off - Disable at exit summary.\n"
  638. " byline - Enable at exit summary by file line number.\n"
  639. " byfunc - Enable at exit summary by function name.\n"
  640. " byfile - Enable at exit summary by file.\n"
  641. "\n"
  642. " Note: byline, byfunc, and byfile are cumulative enables.\n";
  643. return NULL;
  644. case CLI_GENERATE:
  645. return NULL;
  646. }
  647. if (a->argc != 4) {
  648. return CLI_SHOWUSAGE;
  649. }
  650. if (ast_false(a->argv[3])) {
  651. atexit_summary = SUMMARY_OFF;
  652. } else if (!strcasecmp(a->argv[3], "byline")) {
  653. atexit_summary |= SUMMARY_BY_LINE;
  654. } else if (!strcasecmp(a->argv[3], "byfunc")) {
  655. atexit_summary |= SUMMARY_BY_FUNC;
  656. } else if (!strcasecmp(a->argv[3], "byfile")) {
  657. atexit_summary |= SUMMARY_BY_FILE;
  658. } else {
  659. return CLI_SHOWUSAGE;
  660. }
  661. if (atexit_summary) {
  662. buf[0] = '\0';
  663. if (atexit_summary & SUMMARY_BY_LINE) {
  664. strcat(buf, "byline");
  665. }
  666. if (atexit_summary & SUMMARY_BY_FUNC) {
  667. if (buf[0]) {
  668. strcat(buf, " | ");
  669. }
  670. strcat(buf, "byfunc");
  671. }
  672. if (atexit_summary & SUMMARY_BY_FILE) {
  673. if (buf[0]) {
  674. strcat(buf, " | ");
  675. }
  676. strcat(buf, "byfile");
  677. }
  678. } else {
  679. strcpy(buf, "Off");
  680. }
  681. ast_cli(a->fd, "The atexit summary is: %s\n", buf);
  682. return CLI_SUCCESS;
  683. }
  684. /*!
  685. * \internal
  686. * \brief Common summary output at the end of the memory show commands.
  687. *
  688. * \param fd CLI output file descriptor.
  689. * \param whales_len Accumulated size of free large allocations.
  690. * \param minnows_len Accumulated size of free small allocations.
  691. * \param total_len Accumulated size of all current allocations.
  692. * \param selected_len Accumulated size of the selected allocations.
  693. * \param cache_len Accumulated size of the allocations that are part of a cache.
  694. * \param count Number of selected allocations.
  695. *
  696. * \return Nothing
  697. */
  698. static void print_memory_show_common_stats(int fd,
  699. unsigned int whales_len,
  700. unsigned int minnows_len,
  701. unsigned int total_len,
  702. unsigned int selected_len,
  703. unsigned int cache_len,
  704. unsigned int count)
  705. {
  706. if (cache_len) {
  707. ast_cli(fd, "%10u bytes allocated (%u in caches) in %u selected allocations\n\n",
  708. selected_len, cache_len, count);
  709. } else {
  710. ast_cli(fd, "%10u bytes allocated in %u selected allocations\n\n",
  711. selected_len, count);
  712. }
  713. ast_cli(fd, "%10u bytes in all allocations\n", total_len);
  714. ast_cli(fd, "%10u bytes in deferred free large allocations\n", whales_len);
  715. ast_cli(fd, "%10u bytes in deferred free small allocations\n", minnows_len);
  716. ast_cli(fd, "%10u bytes in deferred free allocations\n",
  717. whales_len + minnows_len);
  718. ast_cli(fd, "%10u bytes in all allocations and deferred free allocations\n",
  719. total_len + whales_len + minnows_len);
  720. }
  721. static char *handle_memory_show_allocations(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  722. {
  723. const char *fn = NULL;
  724. struct ast_region *reg;
  725. unsigned int idx;
  726. unsigned int whales_len;
  727. unsigned int minnows_len;
  728. unsigned int total_len = 0;
  729. unsigned int selected_len = 0;
  730. unsigned int cache_len = 0;
  731. unsigned int count = 0;
  732. switch (cmd) {
  733. case CLI_INIT:
  734. e->command = "memory show allocations";
  735. e->usage =
  736. "Usage: memory show allocations [<file>|anomalies]\n"
  737. " Dumps a list of segments of allocated memory.\n"
  738. " Defaults to listing all memory allocations.\n"
  739. " <file> - Restricts output to memory allocated by the file.\n"
  740. " anomalies - Only check for fence violations.\n";
  741. return NULL;
  742. case CLI_GENERATE:
  743. return NULL;
  744. }
  745. if (a->argc == 4) {
  746. fn = a->argv[3];
  747. } else if (a->argc != 3) {
  748. return CLI_SHOWUSAGE;
  749. }
  750. /* Look for historical misspelled option as well. */
  751. if (fn && (!strcasecmp(fn, "anomalies") || !strcasecmp(fn, "anomolies"))) {
  752. regions_check_all_fences();
  753. ast_cli(a->fd, "Anomaly check complete.\n");
  754. return CLI_SUCCESS;
  755. }
  756. ast_mutex_lock(&reglock);
  757. for (idx = 0; idx < ARRAY_LEN(regions); ++idx) {
  758. for (reg = regions[idx]; reg; reg = AST_LIST_NEXT(reg, node)) {
  759. total_len += reg->len;
  760. if (fn && strcasecmp(fn, reg->file)) {
  761. continue;
  762. }
  763. region_check_fences(reg);
  764. ast_cli(a->fd, "%10u bytes allocated%s by %20s() line %5u of %s\n",
  765. (unsigned int) reg->len, reg->cache ? " (cache)" : "",
  766. reg->func, reg->lineno, reg->file);
  767. selected_len += reg->len;
  768. if (reg->cache) {
  769. cache_len += reg->len;
  770. }
  771. ++count;
  772. }
  773. }
  774. whales_len = freed_regions_size(&whales);
  775. minnows_len = freed_regions_size(&minnows);
  776. ast_mutex_unlock(&reglock);
  777. print_memory_show_common_stats(a->fd,
  778. whales_len, minnows_len, total_len,
  779. selected_len, cache_len, count);
  780. return CLI_SUCCESS;
  781. }
  782. static char *handle_memory_show_summary(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  783. {
  784. #define my_max(a, b) ((a) >= (b) ? (a) : (b))
  785. const char *fn = NULL;
  786. int idx;
  787. int cmp;
  788. struct ast_region *reg;
  789. unsigned int whales_len;
  790. unsigned int minnows_len;
  791. unsigned int total_len = 0;
  792. unsigned int selected_len = 0;
  793. unsigned int cache_len = 0;
  794. unsigned int count = 0;
  795. struct file_summary {
  796. struct file_summary *next;
  797. unsigned int len;
  798. unsigned int cache_len;
  799. unsigned int count;
  800. unsigned int lineno;
  801. char name[my_max(sizeof(reg->file), sizeof(reg->func))];
  802. } *list = NULL, *cur, **prev;
  803. switch (cmd) {
  804. case CLI_INIT:
  805. e->command = "memory show summary";
  806. e->usage =
  807. "Usage: memory show summary [<file>]\n"
  808. " Summarizes heap memory allocations by file, or optionally\n"
  809. " by line if a file is specified.\n";
  810. return NULL;
  811. case CLI_GENERATE:
  812. return NULL;
  813. }
  814. if (a->argc == 4) {
  815. fn = a->argv[3];
  816. } else if (a->argc != 3) {
  817. return CLI_SHOWUSAGE;
  818. }
  819. ast_mutex_lock(&reglock);
  820. for (idx = 0; idx < ARRAY_LEN(regions); ++idx) {
  821. for (reg = regions[idx]; reg; reg = AST_LIST_NEXT(reg, node)) {
  822. total_len += reg->len;
  823. if (fn) {
  824. if (strcasecmp(fn, reg->file)) {
  825. continue;
  826. }
  827. /* Sort list by func/lineno. Find existing or place to insert. */
  828. for (prev = &list; (cur = *prev); prev = &cur->next) {
  829. cmp = strcmp(cur->name, reg->func);
  830. if (cmp < 0) {
  831. continue;
  832. }
  833. if (cmp > 0) {
  834. /* Insert before current */
  835. cur = NULL;
  836. break;
  837. }
  838. cmp = cur->lineno - reg->lineno;
  839. if (cmp < 0) {
  840. continue;
  841. }
  842. if (cmp > 0) {
  843. /* Insert before current */
  844. cur = NULL;
  845. }
  846. break;
  847. }
  848. } else {
  849. /* Sort list by filename. Find existing or place to insert. */
  850. for (prev = &list; (cur = *prev); prev = &cur->next) {
  851. cmp = strcmp(cur->name, reg->file);
  852. if (cmp < 0) {
  853. continue;
  854. }
  855. if (cmp > 0) {
  856. /* Insert before current */
  857. cur = NULL;
  858. }
  859. break;
  860. }
  861. }
  862. if (!cur) {
  863. cur = ast_alloca(sizeof(*cur));
  864. memset(cur, 0, sizeof(*cur));
  865. cur->lineno = reg->lineno;
  866. ast_copy_string(cur->name, fn ? reg->func : reg->file, sizeof(cur->name));
  867. cur->next = *prev;
  868. *prev = cur;
  869. }
  870. cur->len += reg->len;
  871. if (reg->cache) {
  872. cur->cache_len += reg->len;
  873. }
  874. ++cur->count;
  875. }
  876. }
  877. whales_len = freed_regions_size(&whales);
  878. minnows_len = freed_regions_size(&minnows);
  879. ast_mutex_unlock(&reglock);
  880. /* Dump the whole list */
  881. for (cur = list; cur; cur = cur->next) {
  882. selected_len += cur->len;
  883. cache_len += cur->cache_len;
  884. count += cur->count;
  885. if (cur->cache_len) {
  886. if (fn) {
  887. ast_cli(a->fd, "%10u bytes (%10u cache) in %10u allocations by %20s() line %5u of %s\n",
  888. cur->len, cur->cache_len, cur->count, cur->name, cur->lineno, fn);
  889. } else {
  890. ast_cli(a->fd, "%10u bytes (%10u cache) in %10u allocations in file %s\n",
  891. cur->len, cur->cache_len, cur->count, cur->name);
  892. }
  893. } else {
  894. if (fn) {
  895. ast_cli(a->fd, "%10u bytes in %10u allocations by %20s() line %5u of %s\n",
  896. cur->len, cur->count, cur->name, cur->lineno, fn);
  897. } else {
  898. ast_cli(a->fd, "%10u bytes in %10u allocations in file %s\n",
  899. cur->len, cur->count, cur->name);
  900. }
  901. }
  902. }
  903. print_memory_show_common_stats(a->fd,
  904. whales_len, minnows_len, total_len,
  905. selected_len, cache_len, count);
  906. return CLI_SUCCESS;
  907. }
  908. static char *handle_memory_backtrace(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  909. {
  910. switch (cmd) {
  911. case CLI_INIT:
  912. e->command = "memory backtrace {on|off}";
  913. e->usage =
  914. "Usage: memory backtrace {on|off}\n"
  915. " Enable dumping an allocation backtrace with memory diagnostics.\n"
  916. " Note that saving the backtrace data for each allocation\n"
  917. " can be CPU intensive.\n";
  918. return NULL;
  919. case CLI_GENERATE:
  920. return NULL;
  921. }
  922. if (a->argc != 3) {
  923. return CLI_SHOWUSAGE;
  924. }
  925. if (ast_true(a->argv[2])) {
  926. backtrace_enabled = 1;
  927. } else if (ast_false(a->argv[2])) {
  928. backtrace_enabled = 0;
  929. } else {
  930. return CLI_SHOWUSAGE;
  931. }
  932. ast_cli(a->fd, "The memory backtrace is: %s\n", backtrace_enabled ? "On" : "Off");
  933. return CLI_SUCCESS;
  934. }
  935. static struct ast_cli_entry cli_memory[] = {
  936. AST_CLI_DEFINE(handle_memory_atexit_list, "Enable memory allocations not freed at exit list."),
  937. AST_CLI_DEFINE(handle_memory_atexit_summary, "Enable memory allocations not freed at exit summary."),
  938. AST_CLI_DEFINE(handle_memory_show_allocations, "Display outstanding memory allocations"),
  939. AST_CLI_DEFINE(handle_memory_show_summary, "Summarize outstanding memory allocations"),
  940. AST_CLI_DEFINE(handle_memory_backtrace, "Enable dumping an allocation backtrace with memory diagnostics."),
  941. };
  942. AST_LIST_HEAD_NOLOCK(region_list, ast_region);
  943. /*!
  944. * \internal
  945. * \brief Convert the allocated regions hash table to a list.
  946. *
  947. * \param list Fill list with the allocated regions.
  948. *
  949. * \details
  950. * Take all allocated regions from the regions[] and put them
  951. * into the list.
  952. *
  953. * \note reglock must be locked before calling.
  954. *
  955. * \note This function is destructive to the regions[] lists.
  956. *
  957. * \return Length of list created.
  958. */
  959. static size_t mm_atexit_hash_list(struct region_list *list)
  960. {
  961. struct ast_region *reg;
  962. size_t total_length;
  963. int idx;
  964. total_length = 0;
  965. for (idx = 0; idx < ARRAY_LEN(regions); ++idx) {
  966. while ((reg = regions[idx])) {
  967. regions[idx] = AST_LIST_NEXT(reg, node);
  968. AST_LIST_NEXT(reg, node) = NULL;
  969. AST_LIST_INSERT_HEAD(list, reg, node);
  970. ++total_length;
  971. }
  972. }
  973. return total_length;
  974. }
  975. /*!
  976. * \internal
  977. * \brief Put the regions list into the allocated regions hash table.
  978. *
  979. * \param list List to put into the allocated regions hash table.
  980. *
  981. * \note reglock must be locked before calling.
  982. *
  983. * \return Nothing
  984. */
  985. static void mm_atexit_hash_restore(struct region_list *list)
  986. {
  987. struct ast_region *reg;
  988. int hash;
  989. while ((reg = AST_LIST_REMOVE_HEAD(list, node))) {
  990. hash = HASH(reg->data);
  991. AST_LIST_NEXT(reg, node) = regions[hash];
  992. regions[hash] = reg;
  993. }
  994. }
  995. /*!
  996. * \internal
  997. * \brief Sort regions comparision.
  998. *
  999. * \param left Region to compare.
  1000. * \param right Region to compare.
  1001. *
  1002. * \retval <0 if left < right
  1003. * \retval =0 if left == right
  1004. * \retval >0 if left > right
  1005. */
  1006. static int mm_atexit_cmp(struct ast_region *left, struct ast_region *right)
  1007. {
  1008. int cmp;
  1009. ptrdiff_t cmp_ptr;
  1010. ssize_t cmp_size;
  1011. /* Sort by filename. */
  1012. cmp = strcmp(left->file, right->file);
  1013. if (cmp) {
  1014. return cmp;
  1015. }
  1016. /* Sort by line number. */
  1017. cmp = left->lineno - right->lineno;
  1018. if (cmp) {
  1019. return cmp;
  1020. }
  1021. /* Sort by allocated size. */
  1022. cmp_size = left->len - right->len;
  1023. if (cmp_size) {
  1024. if (cmp_size < 0) {
  1025. return -1;
  1026. }
  1027. return 1;
  1028. }
  1029. /* Sort by allocated pointers just because. */
  1030. cmp_ptr = left->data - right->data;
  1031. if (cmp_ptr) {
  1032. if (cmp_ptr < 0) {
  1033. return -1;
  1034. }
  1035. return 1;
  1036. }
  1037. return 0;
  1038. }
  1039. /*!
  1040. * \internal
  1041. * \brief Merge the given sorted sublists into sorted order onto the end of the list.
  1042. *
  1043. * \param list Merge sublists onto this list.
  1044. * \param sub1 First sublist to merge.
  1045. * \param sub2 Second sublist to merge.
  1046. *
  1047. * \return Nothing
  1048. */
  1049. static void mm_atexit_list_merge(struct region_list *list, struct region_list *sub1, struct region_list *sub2)
  1050. {
  1051. struct ast_region *reg;
  1052. for (;;) {
  1053. if (AST_LIST_EMPTY(sub1)) {
  1054. /* The remaining sublist goes onto the list. */
  1055. AST_LIST_APPEND_LIST(list, sub2, node);
  1056. break;
  1057. }
  1058. if (AST_LIST_EMPTY(sub2)) {
  1059. /* The remaining sublist goes onto the list. */
  1060. AST_LIST_APPEND_LIST(list, sub1, node);
  1061. break;
  1062. }
  1063. if (mm_atexit_cmp(AST_LIST_FIRST(sub1), AST_LIST_FIRST(sub2)) <= 0) {
  1064. reg = AST_LIST_REMOVE_HEAD(sub1, node);
  1065. } else {
  1066. reg = AST_LIST_REMOVE_HEAD(sub2, node);
  1067. }
  1068. AST_LIST_INSERT_TAIL(list, reg, node);
  1069. }
  1070. }
  1071. /*!
  1072. * \internal
  1073. * \brief Take sublists off of the given list.
  1074. *
  1075. * \param list Source list to remove sublists from the beginning of list.
  1076. * \param sub Array of sublists to fill. (Lists are empty on entry.)
  1077. * \param num_lists Number of lists to remove from the source list.
  1078. * \param size Size of the sublists to remove.
  1079. * \param remaining Remaining number of elements on the source list.
  1080. *
  1081. * \return Nothing
  1082. */
  1083. static void mm_atexit_list_split(struct region_list *list, struct region_list sub[], size_t num_lists, size_t size, size_t *remaining)
  1084. {
  1085. int idx;
  1086. for (idx = 0; idx < num_lists; ++idx) {
  1087. size_t count;
  1088. if (*remaining < size) {
  1089. /* The remaining source list goes onto the sublist. */
  1090. AST_LIST_APPEND_LIST(&sub[idx], list, node);
  1091. *remaining = 0;
  1092. break;
  1093. }
  1094. /* Take a sublist off the beginning of the source list. */
  1095. *remaining -= size;
  1096. for (count = size; count--;) {
  1097. struct ast_region *reg;
  1098. reg = AST_LIST_REMOVE_HEAD(list, node);
  1099. AST_LIST_INSERT_TAIL(&sub[idx], reg, node);
  1100. }
  1101. }
  1102. }
  1103. /*!
  1104. * \internal
  1105. * \brief Sort the regions list using mergesort.
  1106. *
  1107. * \param list Allocated regions list to sort.
  1108. * \param length Length of the list.
  1109. *
  1110. * \return Nothing
  1111. */
  1112. static void mm_atexit_list_sort(struct region_list *list, size_t length)
  1113. {
  1114. /*! Semi-sorted merged list. */
  1115. struct region_list merged = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
  1116. /*! Sublists to merge. (Can only merge two sublists at this time.) */
  1117. struct region_list sub[2] = {
  1118. AST_LIST_HEAD_NOLOCK_INIT_VALUE,
  1119. AST_LIST_HEAD_NOLOCK_INIT_VALUE
  1120. };
  1121. /*! Sublist size. */
  1122. size_t size = 1;
  1123. /*! Remaining elements in the list. */
  1124. size_t remaining;
  1125. /*! Number of sublist merge passes to process the list. */
  1126. int passes;
  1127. for (;;) {
  1128. remaining = length;
  1129. passes = 0;
  1130. while (!AST_LIST_EMPTY(list)) {
  1131. mm_atexit_list_split(list, sub, ARRAY_LEN(sub), size, &remaining);
  1132. mm_atexit_list_merge(&merged, &sub[0], &sub[1]);
  1133. ++passes;
  1134. }
  1135. AST_LIST_APPEND_LIST(list, &merged, node);
  1136. if (passes <= 1) {
  1137. /* The list is now sorted. */
  1138. break;
  1139. }
  1140. /* Double the sublist size to remove for next round. */
  1141. size <<= 1;
  1142. }
  1143. }
  1144. /*!
  1145. * \internal
  1146. * \brief List all regions currently allocated.
  1147. *
  1148. * \param alloced regions list.
  1149. *
  1150. * \return Nothing
  1151. */
  1152. static void mm_atexit_regions_list(struct region_list *alloced)
  1153. {
  1154. struct ast_region *reg;
  1155. AST_LIST_TRAVERSE(alloced, reg, node) {
  1156. astmm_log("%s %s() line %u: %u bytes%s at %p\n",
  1157. reg->file, reg->func, reg->lineno,
  1158. (unsigned int) reg->len, reg->cache ? " (cache)" : "", reg->data);
  1159. }
  1160. }
  1161. /*!
  1162. * \internal
  1163. * \brief Summarize all regions currently allocated.
  1164. *
  1165. * \param alloced Sorted regions list.
  1166. *
  1167. * \return Nothing
  1168. */
  1169. static void mm_atexit_regions_summary(struct region_list *alloced)
  1170. {
  1171. struct ast_region *reg;
  1172. struct ast_region *next;
  1173. struct {
  1174. unsigned int count;
  1175. unsigned int len;
  1176. unsigned int cache_len;
  1177. } by_line, by_func, by_file, total;
  1178. by_line.count = 0;
  1179. by_line.len = 0;
  1180. by_line.cache_len = 0;
  1181. by_func.count = 0;
  1182. by_func.len = 0;
  1183. by_func.cache_len = 0;
  1184. by_file.count = 0;
  1185. by_file.len = 0;
  1186. by_file.cache_len = 0;
  1187. total.count = 0;
  1188. total.len = 0;
  1189. total.cache_len = 0;
  1190. AST_LIST_TRAVERSE(alloced, reg, node) {
  1191. next = AST_LIST_NEXT(reg, node);
  1192. ++by_line.count;
  1193. by_line.len += reg->len;
  1194. if (reg->cache) {
  1195. by_line.cache_len += reg->len;
  1196. }
  1197. if (next && !strcmp(reg->file, next->file) && reg->lineno == next->lineno) {
  1198. continue;
  1199. }
  1200. if (atexit_summary & SUMMARY_BY_LINE) {
  1201. if (by_line.cache_len) {
  1202. astmm_log("%10u bytes (%u in caches) in %u allocations. %s %s() line %u\n",
  1203. by_line.len, by_line.cache_len, by_line.count, reg->file, reg->func, reg->lineno);
  1204. } else {
  1205. astmm_log("%10u bytes in %5u allocations. %s %s() line %u\n",
  1206. by_line.len, by_line.count, reg->file, reg->func, reg->lineno);
  1207. }
  1208. }
  1209. by_func.count += by_line.count;
  1210. by_func.len += by_line.len;
  1211. by_func.cache_len += by_line.cache_len;
  1212. by_line.count = 0;
  1213. by_line.len = 0;
  1214. by_line.cache_len = 0;
  1215. if (next && !strcmp(reg->file, next->file) && !strcmp(reg->func, next->func)) {
  1216. continue;
  1217. }
  1218. if (atexit_summary & SUMMARY_BY_FUNC) {
  1219. if (by_func.cache_len) {
  1220. astmm_log("%10u bytes (%u in caches) in %u allocations. %s %s()\n",
  1221. by_func.len, by_func.cache_len, by_func.count, reg->file, reg->func);
  1222. } else {
  1223. astmm_log("%10u bytes in %5u allocations. %s %s()\n",
  1224. by_func.len, by_func.count, reg->file, reg->func);
  1225. }
  1226. }
  1227. by_file.count += by_func.count;
  1228. by_file.len += by_func.len;
  1229. by_file.cache_len += by_func.cache_len;
  1230. by_func.count = 0;
  1231. by_func.len = 0;
  1232. by_func.cache_len = 0;
  1233. if (next && !strcmp(reg->file, next->file)) {
  1234. continue;
  1235. }
  1236. if (atexit_summary & SUMMARY_BY_FILE) {
  1237. if (by_file.cache_len) {
  1238. astmm_log("%10u bytes (%u in caches) in %u allocations. %s\n",
  1239. by_file.len, by_file.cache_len, by_file.count, reg->file);
  1240. } else {
  1241. astmm_log("%10u bytes in %5u allocations. %s\n",
  1242. by_file.len, by_file.count, reg->file);
  1243. }
  1244. }
  1245. total.count += by_file.count;
  1246. total.len += by_file.len;
  1247. total.cache_len += by_file.cache_len;
  1248. by_file.count = 0;
  1249. by_file.len = 0;
  1250. by_file.cache_len = 0;
  1251. }
  1252. if (total.cache_len) {
  1253. astmm_log("%u bytes (%u in caches) in %u allocations.\n",
  1254. total.len, total.cache_len, total.count);
  1255. } else {
  1256. astmm_log("%u bytes in %u allocations.\n", total.len, total.count);
  1257. }
  1258. }
  1259. /*!
  1260. * \internal
  1261. * \brief Dump the memory allocations atexit.
  1262. *
  1263. * \note reglock must be locked before calling.
  1264. *
  1265. * \return Nothing
  1266. */
  1267. static void mm_atexit_dump(void)
  1268. {
  1269. struct region_list alloced_atexit = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
  1270. size_t length;
  1271. length = mm_atexit_hash_list(&alloced_atexit);
  1272. if (!length) {
  1273. /* Wow! This is amazing! */
  1274. astmm_log("Exiting with all memory freed.\n");
  1275. return;
  1276. }
  1277. mm_atexit_list_sort(&alloced_atexit, length);
  1278. astmm_log("Exiting with the following memory not freed:\n");
  1279. if (atexit_list) {
  1280. mm_atexit_regions_list(&alloced_atexit);
  1281. }
  1282. if (atexit_summary) {
  1283. mm_atexit_regions_summary(&alloced_atexit);
  1284. }
  1285. /*
  1286. * Put the alloced list back into regions[].
  1287. *
  1288. * We have do this because we can get called before all other
  1289. * threads have terminated.
  1290. */
  1291. mm_atexit_hash_restore(&alloced_atexit);
  1292. }
  1293. /*!
  1294. * \internal
  1295. * \return Nothing
  1296. */
  1297. static void mm_atexit_final(void)
  1298. {
  1299. FILE *log;
  1300. /* Only wait if we want atexit allocation dumps. */
  1301. if (atexit_list || atexit_summary) {
  1302. fprintf(stderr, "Waiting 10 seconds to let other threads die.\n");
  1303. sleep(10);
  1304. }
  1305. regions_check_all_fences();
  1306. /* Flush all delayed memory free circular arrays. */
  1307. freed_regions_flush(&whales);
  1308. freed_regions_flush(&minnows);
  1309. /* Peform atexit allocation dumps. */
  1310. if (atexit_list || atexit_summary) {
  1311. ast_mutex_lock(&reglock);
  1312. mm_atexit_dump();
  1313. ast_mutex_unlock(&reglock);
  1314. }
  1315. /* Close the log file. */
  1316. log = mmlog;
  1317. mmlog = NULL;
  1318. if (log) {
  1319. fclose(log);
  1320. }
  1321. }
  1322. /*!
  1323. * \brief Initialize malloc debug phase 1.
  1324. *
  1325. * \note Must be called first thing in main().
  1326. *
  1327. * \return Nothing
  1328. */
  1329. void __ast_mm_init_phase_1(void)
  1330. {
  1331. atexit(mm_atexit_final);
  1332. }
  1333. /*!
  1334. * \internal
  1335. * \return Nothing
  1336. */
  1337. static void mm_atexit_ast(void)
  1338. {
  1339. ast_cli_unregister_multiple(cli_memory, ARRAY_LEN(cli_memory));
  1340. }
  1341. /*!
  1342. * \brief Initialize malloc debug phase 2.
  1343. *
  1344. * \return Nothing
  1345. */
  1346. void __ast_mm_init_phase_2(void)
  1347. {
  1348. char filename[PATH_MAX];
  1349. ast_cli_register_multiple(cli_memory, ARRAY_LEN(cli_memory));
  1350. snprintf(filename, sizeof(filename), "%s/mmlog", ast_config_AST_LOG_DIR);
  1351. ast_verb(1, "Asterisk Malloc Debugger Started (see %s))\n", filename);
  1352. mmlog = fopen(filename, "a+");
  1353. if (mmlog) {
  1354. fprintf(mmlog, "%ld - New session\n", (long) time(NULL));
  1355. fflush(mmlog);
  1356. } else {
  1357. ast_log(LOG_ERROR, "Could not open malloc debug log file: %s\n", filename);
  1358. }
  1359. ast_register_cleanup(mm_atexit_ast);
  1360. }
  1361. #endif /* defined(__AST_DEBUG_MALLOC) */