astmm.c 35 KB

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