memusage.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. /* Profile heap and stack memory usage of running program.
  2. Copyright (C) 1998-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, see
  15. <http://www.gnu.org/licenses/>. */
  16. #include <assert.h>
  17. #include <atomic.h>
  18. #include <dlfcn.h>
  19. #include <errno.h>
  20. #include <fcntl.h>
  21. #include <inttypes.h>
  22. #include <signal.h>
  23. #include <stdarg.h>
  24. #include <stdbool.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <unistd.h>
  29. #include <stdint.h>
  30. #include <sys/mman.h>
  31. #include <sys/time.h>
  32. #include <memusage.h>
  33. /* Pointer to the real functions. These are determined used `dlsym'
  34. when really needed. */
  35. static void *(*mallocp)(size_t);
  36. static void *(*reallocp) (void *, size_t);
  37. static void *(*callocp) (size_t, size_t);
  38. static void (*freep) (void *);
  39. static void *(*mmapp) (void *, size_t, int, int, int, off_t);
  40. static void *(*mmap64p) (void *, size_t, int, int, int, off64_t);
  41. static int (*munmapp) (void *, size_t);
  42. static void *(*mremapp) (void *, size_t, size_t, int, void *);
  43. enum
  44. {
  45. idx_malloc = 0,
  46. idx_realloc,
  47. idx_calloc,
  48. idx_free,
  49. idx_mmap_r,
  50. idx_mmap_w,
  51. idx_mmap_a,
  52. idx_mremap,
  53. idx_munmap,
  54. idx_last
  55. };
  56. struct header
  57. {
  58. size_t length;
  59. size_t magic;
  60. };
  61. #define MAGIC 0xfeedbeaf
  62. static memusage_cntr_t calls[idx_last];
  63. static memusage_cntr_t failed[idx_last];
  64. static memusage_size_t total[idx_last];
  65. static memusage_size_t grand_total;
  66. static memusage_cntr_t histogram[65536 / 16];
  67. static memusage_cntr_t large;
  68. static memusage_cntr_t calls_total;
  69. static memusage_cntr_t inplace;
  70. static memusage_cntr_t decreasing;
  71. static memusage_cntr_t realloc_free;
  72. static memusage_cntr_t inplace_mremap;
  73. static memusage_cntr_t decreasing_mremap;
  74. static memusage_size_t current_heap;
  75. static memusage_size_t peak_use[3];
  76. static __thread uintptr_t start_sp;
  77. /* A few macros to make the source more readable. */
  78. #define peak_heap peak_use[0]
  79. #define peak_stack peak_use[1]
  80. #define peak_total peak_use[2]
  81. #define DEFAULT_BUFFER_SIZE 32768
  82. static size_t buffer_size;
  83. static int fd = -1;
  84. static bool not_me;
  85. static int initialized;
  86. static bool trace_mmap;
  87. extern const char *__progname;
  88. struct entry
  89. {
  90. uint64_t heap;
  91. uint64_t stack;
  92. uint32_t time_low;
  93. uint32_t time_high;
  94. };
  95. static struct entry buffer[2 * DEFAULT_BUFFER_SIZE];
  96. static uatomic32_t buffer_cnt;
  97. static struct entry first;
  98. /* Update the global data after a successful function call. */
  99. static void
  100. update_data (struct header *result, size_t len, size_t old_len)
  101. {
  102. if (result != NULL)
  103. {
  104. /* Record the information we need and mark the block using a
  105. magic number. */
  106. result->length = len;
  107. result->magic = MAGIC;
  108. }
  109. /* Compute current heap usage and compare it with the maximum value. */
  110. memusage_size_t heap
  111. = catomic_exchange_and_add (&current_heap, len - old_len) + len - old_len;
  112. catomic_max (&peak_heap, heap);
  113. /* Compute current stack usage and compare it with the maximum
  114. value. The base stack pointer might not be set if this is not
  115. the main thread and it is the first call to any of these
  116. functions. */
  117. if (__glibc_unlikely (!start_sp))
  118. start_sp = GETSP ();
  119. uintptr_t sp = GETSP ();
  120. #ifdef STACK_GROWS_UPWARD
  121. /* This can happen in threads where we didn't catch the thread's
  122. stack early enough. */
  123. if (__glibc_unlikely (sp < start_sp))
  124. start_sp = sp;
  125. size_t current_stack = sp - start_sp;
  126. #else
  127. /* This can happen in threads where we didn't catch the thread's
  128. stack early enough. */
  129. if (__glibc_unlikely (sp > start_sp))
  130. start_sp = sp;
  131. size_t current_stack = start_sp - sp;
  132. #endif
  133. catomic_max (&peak_stack, current_stack);
  134. /* Add up heap and stack usage and compare it with the maximum value. */
  135. catomic_max (&peak_total, heap + current_stack);
  136. /* Store the value only if we are writing to a file. */
  137. if (fd != -1)
  138. {
  139. uatomic32_t idx = catomic_exchange_and_add (&buffer_cnt, 1);
  140. if (idx + 1 >= 2 * buffer_size)
  141. {
  142. /* We try to reset the counter to the correct range. If
  143. this fails because of another thread increasing the
  144. counter it does not matter since that thread will take
  145. care of the correction. */
  146. uatomic32_t reset = (idx + 1) % (2 * buffer_size);
  147. catomic_compare_and_exchange_val_acq (&buffer_cnt, reset, idx + 1);
  148. if (idx >= 2 * buffer_size)
  149. idx = reset - 1;
  150. }
  151. assert (idx < 2 * DEFAULT_BUFFER_SIZE);
  152. buffer[idx].heap = current_heap;
  153. buffer[idx].stack = current_stack;
  154. GETTIME (buffer[idx].time_low, buffer[idx].time_high);
  155. /* Write out buffer if it is full. */
  156. if (idx + 1 == buffer_size)
  157. write (fd, buffer, buffer_size * sizeof (struct entry));
  158. else if (idx + 1 == 2 * buffer_size)
  159. write (fd, &buffer[buffer_size], buffer_size * sizeof (struct entry));
  160. }
  161. }
  162. /* Interrupt handler. */
  163. static void
  164. int_handler (int signo)
  165. {
  166. /* Nothing gets allocated. Just record the stack pointer position. */
  167. update_data (NULL, 0, 0);
  168. }
  169. /* Find out whether this is the program we are supposed to profile.
  170. For this the name in the variable `__progname' must match the one
  171. given in the environment variable MEMUSAGE_PROG_NAME. If the variable
  172. is not present every program assumes it should be profiling.
  173. If this is the program open a file descriptor to the output file.
  174. We will write to it whenever the buffer overflows. The name of the
  175. output file is determined by the environment variable MEMUSAGE_OUTPUT.
  176. If the environment variable MEMUSAGE_BUFFER_SIZE is set its numerical
  177. value determines the size of the internal buffer. The number gives
  178. the number of elements in the buffer. By setting the number to one
  179. one effectively selects unbuffered operation.
  180. If MEMUSAGE_NO_TIMER is not present an alarm handler is installed
  181. which at the highest possible frequency records the stack pointer. */
  182. static void
  183. me (void)
  184. {
  185. const char *env = getenv ("MEMUSAGE_PROG_NAME");
  186. size_t prog_len = strlen (__progname);
  187. initialized = -1;
  188. mallocp = (void *(*)(size_t))dlsym (RTLD_NEXT, "malloc");
  189. reallocp = (void *(*)(void *, size_t))dlsym (RTLD_NEXT, "realloc");
  190. callocp = (void *(*)(size_t, size_t))dlsym (RTLD_NEXT, "calloc");
  191. freep = (void (*)(void *))dlsym (RTLD_NEXT, "free");
  192. mmapp = (void *(*)(void *, size_t, int, int, int, off_t))dlsym (RTLD_NEXT,
  193. "mmap");
  194. mmap64p =
  195. (void *(*)(void *, size_t, int, int, int, off64_t))dlsym (RTLD_NEXT,
  196. "mmap64");
  197. mremapp = (void *(*)(void *, size_t, size_t, int, void *))dlsym (RTLD_NEXT,
  198. "mremap");
  199. munmapp = (int (*)(void *, size_t))dlsym (RTLD_NEXT, "munmap");
  200. initialized = 1;
  201. if (env != NULL)
  202. {
  203. /* Check for program name. */
  204. size_t len = strlen (env);
  205. if (len > prog_len || strcmp (env, &__progname[prog_len - len]) != 0
  206. || (prog_len != len && __progname[prog_len - len - 1] != '/'))
  207. not_me = true;
  208. }
  209. /* Only open the file if it's really us. */
  210. if (!not_me && fd == -1)
  211. {
  212. const char *outname;
  213. if (!start_sp)
  214. start_sp = GETSP ();
  215. outname = getenv ("MEMUSAGE_OUTPUT");
  216. if (outname != NULL && outname[0] != '\0'
  217. && (access (outname, R_OK | W_OK) == 0 || errno == ENOENT))
  218. {
  219. fd = creat64 (outname, 0666);
  220. if (fd == -1)
  221. /* Don't do anything in future calls if we cannot write to
  222. the output file. */
  223. not_me = true;
  224. else
  225. {
  226. /* Write the first entry. */
  227. first.heap = 0;
  228. first.stack = 0;
  229. GETTIME (first.time_low, first.time_high);
  230. /* Write it two times since we need the starting and end time. */
  231. write (fd, &first, sizeof (first));
  232. write (fd, &first, sizeof (first));
  233. /* Determine the buffer size. We use the default if the
  234. environment variable is not present. */
  235. buffer_size = DEFAULT_BUFFER_SIZE;
  236. const char *str_buffer_size = getenv ("MEMUSAGE_BUFFER_SIZE");
  237. if (str_buffer_size != NULL)
  238. {
  239. buffer_size = atoi (str_buffer_size);
  240. if (buffer_size == 0 || buffer_size > DEFAULT_BUFFER_SIZE)
  241. buffer_size = DEFAULT_BUFFER_SIZE;
  242. }
  243. /* Possibly enable timer-based stack pointer retrieval. */
  244. if (getenv ("MEMUSAGE_NO_TIMER") == NULL)
  245. {
  246. struct sigaction act;
  247. act.sa_handler = (sighandler_t) &int_handler;
  248. act.sa_flags = SA_RESTART;
  249. sigfillset (&act.sa_mask);
  250. if (sigaction (SIGPROF, &act, NULL) >= 0)
  251. {
  252. struct itimerval timer;
  253. timer.it_value.tv_sec = 0;
  254. timer.it_value.tv_usec = 1;
  255. timer.it_interval = timer.it_value;
  256. setitimer (ITIMER_PROF, &timer, NULL);
  257. }
  258. }
  259. }
  260. }
  261. if (!not_me && getenv ("MEMUSAGE_TRACE_MMAP") != NULL)
  262. trace_mmap = true;
  263. }
  264. }
  265. /* Record the initial stack position. */
  266. static void
  267. __attribute__ ((constructor))
  268. init (void)
  269. {
  270. start_sp = GETSP ();
  271. if (!initialized)
  272. me ();
  273. }
  274. /* `malloc' replacement. We keep track of the memory usage if this is the
  275. correct program. */
  276. void *
  277. malloc (size_t len)
  278. {
  279. struct header *result = NULL;
  280. /* Determine real implementation if not already happened. */
  281. if (__glibc_unlikely (initialized <= 0))
  282. {
  283. if (initialized == -1)
  284. return NULL;
  285. me ();
  286. }
  287. /* If this is not the correct program just use the normal function. */
  288. if (not_me)
  289. return (*mallocp)(len);
  290. /* Keep track of number of calls. */
  291. catomic_increment (&calls[idx_malloc]);
  292. /* Keep track of total memory consumption for `malloc'. */
  293. catomic_add (&total[idx_malloc], len);
  294. /* Keep track of total memory requirement. */
  295. catomic_add (&grand_total, len);
  296. /* Remember the size of the request. */
  297. if (len < 65536)
  298. catomic_increment (&histogram[len / 16]);
  299. else
  300. catomic_increment (&large);
  301. /* Total number of calls of any of the functions. */
  302. catomic_increment (&calls_total);
  303. /* Do the real work. */
  304. result = (struct header *) (*mallocp)(len + sizeof (struct header));
  305. if (result == NULL)
  306. {
  307. catomic_increment (&failed[idx_malloc]);
  308. return NULL;
  309. }
  310. /* Update the allocation data and write out the records if necessary. */
  311. update_data (result, len, 0);
  312. /* Return the pointer to the user buffer. */
  313. return (void *) (result + 1);
  314. }
  315. /* `realloc' replacement. We keep track of the memory usage if this is the
  316. correct program. */
  317. void *
  318. realloc (void *old, size_t len)
  319. {
  320. struct header *result = NULL;
  321. struct header *real;
  322. size_t old_len;
  323. /* Determine real implementation if not already happened. */
  324. if (__glibc_unlikely (initialized <= 0))
  325. {
  326. if (initialized == -1)
  327. return NULL;
  328. me ();
  329. }
  330. /* If this is not the correct program just use the normal function. */
  331. if (not_me)
  332. return (*reallocp)(old, len);
  333. if (old == NULL)
  334. {
  335. /* This is really a `malloc' call. */
  336. real = NULL;
  337. old_len = 0;
  338. }
  339. else
  340. {
  341. real = ((struct header *) old) - 1;
  342. if (real->magic != MAGIC)
  343. /* This is no memory allocated here. */
  344. return (*reallocp)(old, len);
  345. old_len = real->length;
  346. }
  347. /* Keep track of number of calls. */
  348. catomic_increment (&calls[idx_realloc]);
  349. if (len > old_len)
  350. {
  351. /* Keep track of total memory consumption for `realloc'. */
  352. catomic_add (&total[idx_realloc], len - old_len);
  353. /* Keep track of total memory requirement. */
  354. catomic_add (&grand_total, len - old_len);
  355. }
  356. if (len == 0 && old != NULL)
  357. {
  358. /* Special case. */
  359. catomic_increment (&realloc_free);
  360. /* Keep track of total memory freed using `free'. */
  361. catomic_add (&total[idx_free], real->length);
  362. /* Update the allocation data and write out the records if necessary. */
  363. update_data (NULL, 0, old_len);
  364. /* Do the real work. */
  365. (*freep) (real);
  366. return NULL;
  367. }
  368. /* Remember the size of the request. */
  369. if (len < 65536)
  370. catomic_increment (&histogram[len / 16]);
  371. else
  372. catomic_increment (&large);
  373. /* Total number of calls of any of the functions. */
  374. catomic_increment (&calls_total);
  375. /* Do the real work. */
  376. result = (struct header *) (*reallocp)(real, len + sizeof (struct header));
  377. if (result == NULL)
  378. {
  379. catomic_increment (&failed[idx_realloc]);
  380. return NULL;
  381. }
  382. /* Record whether the reduction/increase happened in place. */
  383. if (real == result)
  384. catomic_increment (&inplace);
  385. /* Was the buffer increased? */
  386. if (old_len > len)
  387. catomic_increment (&decreasing);
  388. /* Update the allocation data and write out the records if necessary. */
  389. update_data (result, len, old_len);
  390. /* Return the pointer to the user buffer. */
  391. return (void *) (result + 1);
  392. }
  393. /* `calloc' replacement. We keep track of the memory usage if this is the
  394. correct program. */
  395. void *
  396. calloc (size_t n, size_t len)
  397. {
  398. struct header *result;
  399. size_t size = n * len;
  400. /* Determine real implementation if not already happened. */
  401. if (__glibc_unlikely (initialized <= 0))
  402. {
  403. if (initialized == -1)
  404. return NULL;
  405. me ();
  406. }
  407. /* If this is not the correct program just use the normal function. */
  408. if (not_me)
  409. return (*callocp)(n, len);
  410. /* Keep track of number of calls. */
  411. catomic_increment (&calls[idx_calloc]);
  412. /* Keep track of total memory consumption for `calloc'. */
  413. catomic_add (&total[idx_calloc], size);
  414. /* Keep track of total memory requirement. */
  415. catomic_add (&grand_total, size);
  416. /* Remember the size of the request. */
  417. if (size < 65536)
  418. catomic_increment (&histogram[size / 16]);
  419. else
  420. catomic_increment (&large);
  421. /* Total number of calls of any of the functions. */
  422. ++calls_total;
  423. /* Do the real work. */
  424. result = (struct header *) (*mallocp)(size + sizeof (struct header));
  425. if (result == NULL)
  426. {
  427. catomic_increment (&failed[idx_calloc]);
  428. return NULL;
  429. }
  430. /* Update the allocation data and write out the records if necessary. */
  431. update_data (result, size, 0);
  432. /* Do what `calloc' would have done and return the buffer to the caller. */
  433. return memset (result + 1, '\0', size);
  434. }
  435. /* `free' replacement. We keep track of the memory usage if this is the
  436. correct program. */
  437. void
  438. free (void *ptr)
  439. {
  440. struct header *real;
  441. /* Determine real implementation if not already happened. */
  442. if (__glibc_unlikely (initialized <= 0))
  443. {
  444. if (initialized == -1)
  445. return;
  446. me ();
  447. }
  448. /* If this is not the correct program just use the normal function. */
  449. if (not_me)
  450. {
  451. (*freep) (ptr);
  452. return;
  453. }
  454. /* `free (NULL)' has no effect. */
  455. if (ptr == NULL)
  456. {
  457. catomic_increment (&calls[idx_free]);
  458. return;
  459. }
  460. /* Determine the pointer to the header. */
  461. real = ((struct header *) ptr) - 1;
  462. if (real->magic != MAGIC)
  463. {
  464. /* This block wasn't allocated here. */
  465. (*freep) (ptr);
  466. return;
  467. }
  468. /* Keep track of number of calls. */
  469. catomic_increment (&calls[idx_free]);
  470. /* Keep track of total memory freed using `free'. */
  471. catomic_add (&total[idx_free], real->length);
  472. /* Update the allocation data and write out the records if necessary. */
  473. update_data (NULL, 0, real->length);
  474. /* Do the real work. */
  475. (*freep) (real);
  476. }
  477. /* `mmap' replacement. We do not have to keep track of the size since
  478. `munmap' will get it as a parameter. */
  479. void *
  480. mmap (void *start, size_t len, int prot, int flags, int fd, off_t offset)
  481. {
  482. void *result = NULL;
  483. /* Determine real implementation if not already happened. */
  484. if (__glibc_unlikely (initialized <= 0))
  485. {
  486. if (initialized == -1)
  487. return NULL;
  488. me ();
  489. }
  490. /* Always get a block. We don't need extra memory. */
  491. result = (*mmapp)(start, len, prot, flags, fd, offset);
  492. if (!not_me && trace_mmap)
  493. {
  494. int idx = (flags & MAP_ANON
  495. ? idx_mmap_a : prot & PROT_WRITE ? idx_mmap_w : idx_mmap_r);
  496. /* Keep track of number of calls. */
  497. catomic_increment (&calls[idx]);
  498. /* Keep track of total memory consumption for `malloc'. */
  499. catomic_add (&total[idx], len);
  500. /* Keep track of total memory requirement. */
  501. catomic_add (&grand_total, len);
  502. /* Remember the size of the request. */
  503. if (len < 65536)
  504. catomic_increment (&histogram[len / 16]);
  505. else
  506. catomic_increment (&large);
  507. /* Total number of calls of any of the functions. */
  508. catomic_increment (&calls_total);
  509. /* Check for failures. */
  510. if (result == NULL)
  511. catomic_increment (&failed[idx]);
  512. else if (idx == idx_mmap_w)
  513. /* Update the allocation data and write out the records if
  514. necessary. Note the first parameter is NULL which means
  515. the size is not tracked. */
  516. update_data (NULL, len, 0);
  517. }
  518. /* Return the pointer to the user buffer. */
  519. return result;
  520. }
  521. /* `mmap64' replacement. We do not have to keep track of the size since
  522. `munmap' will get it as a parameter. */
  523. void *
  524. mmap64 (void *start, size_t len, int prot, int flags, int fd, off64_t offset)
  525. {
  526. void *result = NULL;
  527. /* Determine real implementation if not already happened. */
  528. if (__glibc_unlikely (initialized <= 0))
  529. {
  530. if (initialized == -1)
  531. return NULL;
  532. me ();
  533. }
  534. /* Always get a block. We don't need extra memory. */
  535. result = (*mmap64p)(start, len, prot, flags, fd, offset);
  536. if (!not_me && trace_mmap)
  537. {
  538. int idx = (flags & MAP_ANON
  539. ? idx_mmap_a : prot & PROT_WRITE ? idx_mmap_w : idx_mmap_r);
  540. /* Keep track of number of calls. */
  541. catomic_increment (&calls[idx]);
  542. /* Keep track of total memory consumption for `malloc'. */
  543. catomic_add (&total[idx], len);
  544. /* Keep track of total memory requirement. */
  545. catomic_add (&grand_total, len);
  546. /* Remember the size of the request. */
  547. if (len < 65536)
  548. catomic_increment (&histogram[len / 16]);
  549. else
  550. catomic_increment (&large);
  551. /* Total number of calls of any of the functions. */
  552. catomic_increment (&calls_total);
  553. /* Check for failures. */
  554. if (result == NULL)
  555. catomic_increment (&failed[idx]);
  556. else if (idx == idx_mmap_w)
  557. /* Update the allocation data and write out the records if
  558. necessary. Note the first parameter is NULL which means
  559. the size is not tracked. */
  560. update_data (NULL, len, 0);
  561. }
  562. /* Return the pointer to the user buffer. */
  563. return result;
  564. }
  565. /* `mremap' replacement. We do not have to keep track of the size since
  566. `munmap' will get it as a parameter. */
  567. void *
  568. mremap (void *start, size_t old_len, size_t len, int flags, ...)
  569. {
  570. void *result = NULL;
  571. va_list ap;
  572. va_start (ap, flags);
  573. void *newaddr = (flags & MREMAP_FIXED) ? va_arg (ap, void *) : NULL;
  574. va_end (ap);
  575. /* Determine real implementation if not already happened. */
  576. if (__glibc_unlikely (initialized <= 0))
  577. {
  578. if (initialized == -1)
  579. return NULL;
  580. me ();
  581. }
  582. /* Always get a block. We don't need extra memory. */
  583. result = (*mremapp)(start, old_len, len, flags, newaddr);
  584. if (!not_me && trace_mmap)
  585. {
  586. /* Keep track of number of calls. */
  587. catomic_increment (&calls[idx_mremap]);
  588. if (len > old_len)
  589. {
  590. /* Keep track of total memory consumption for `malloc'. */
  591. catomic_add (&total[idx_mremap], len - old_len);
  592. /* Keep track of total memory requirement. */
  593. catomic_add (&grand_total, len - old_len);
  594. }
  595. /* Remember the size of the request. */
  596. if (len < 65536)
  597. catomic_increment (&histogram[len / 16]);
  598. else
  599. catomic_increment (&large);
  600. /* Total number of calls of any of the functions. */
  601. catomic_increment (&calls_total);
  602. /* Check for failures. */
  603. if (result == NULL)
  604. catomic_increment (&failed[idx_mremap]);
  605. else
  606. {
  607. /* Record whether the reduction/increase happened in place. */
  608. if (start == result)
  609. catomic_increment (&inplace_mremap);
  610. /* Was the buffer increased? */
  611. if (old_len > len)
  612. catomic_increment (&decreasing_mremap);
  613. /* Update the allocation data and write out the records if
  614. necessary. Note the first parameter is NULL which means
  615. the size is not tracked. */
  616. update_data (NULL, len, old_len);
  617. }
  618. }
  619. /* Return the pointer to the user buffer. */
  620. return result;
  621. }
  622. /* `munmap' replacement. */
  623. int
  624. munmap (void *start, size_t len)
  625. {
  626. int result;
  627. /* Determine real implementation if not already happened. */
  628. if (__glibc_unlikely (initialized <= 0))
  629. {
  630. if (initialized == -1)
  631. return -1;
  632. me ();
  633. }
  634. /* Do the real work. */
  635. result = (*munmapp)(start, len);
  636. if (!not_me && trace_mmap)
  637. {
  638. /* Keep track of number of calls. */
  639. catomic_increment (&calls[idx_munmap]);
  640. if (__glibc_likely (result == 0))
  641. {
  642. /* Keep track of total memory freed using `free'. */
  643. catomic_add (&total[idx_munmap], len);
  644. /* Update the allocation data and write out the records if
  645. necessary. */
  646. update_data (NULL, 0, len);
  647. }
  648. else
  649. catomic_increment (&failed[idx_munmap]);
  650. }
  651. return result;
  652. }
  653. /* Write some statistics to standard error. */
  654. static void
  655. __attribute__ ((destructor))
  656. dest (void)
  657. {
  658. int percent, cnt;
  659. unsigned long int maxcalls;
  660. /* If we haven't done anything here just return. */
  661. if (not_me)
  662. return;
  663. /* If we should call any of the memory functions don't do any profiling. */
  664. not_me = true;
  665. /* Finish the output file. */
  666. if (fd != -1)
  667. {
  668. /* Write the partially filled buffer. */
  669. if (buffer_cnt > buffer_size)
  670. write (fd, buffer + buffer_size,
  671. (buffer_cnt - buffer_size) * sizeof (struct entry));
  672. else
  673. write (fd, buffer, buffer_cnt * sizeof (struct entry));
  674. /* Go back to the beginning of the file. We allocated two records
  675. here when we opened the file. */
  676. lseek (fd, 0, SEEK_SET);
  677. /* Write out a record containing the total size. */
  678. first.stack = peak_total;
  679. write (fd, &first, sizeof (struct entry));
  680. /* Write out another record containing the maximum for heap and
  681. stack. */
  682. first.heap = peak_heap;
  683. first.stack = peak_stack;
  684. GETTIME (first.time_low, first.time_high);
  685. write (fd, &first, sizeof (struct entry));
  686. /* Close the file. */
  687. close (fd);
  688. fd = -1;
  689. }
  690. /* Write a colorful statistic. */
  691. fprintf (stderr, "\n\
  692. \e[01;32mMemory usage summary:\e[0;0m heap total: %llu, heap peak: %lu, stack peak: %lu\n\
  693. \e[04;34m total calls total memory failed calls\e[0m\n\
  694. \e[00;34m malloc|\e[0m %10lu %12llu %s%12lu\e[00;00m\n\
  695. \e[00;34mrealloc|\e[0m %10lu %12llu %s%12lu\e[00;00m (nomove:%ld, dec:%ld, free:%ld)\n\
  696. \e[00;34m calloc|\e[0m %10lu %12llu %s%12lu\e[00;00m\n\
  697. \e[00;34m free|\e[0m %10lu %12llu\n",
  698. (unsigned long long int) grand_total, (unsigned long int) peak_heap,
  699. (unsigned long int) peak_stack,
  700. (unsigned long int) calls[idx_malloc],
  701. (unsigned long long int) total[idx_malloc],
  702. failed[idx_malloc] ? "\e[01;41m" : "",
  703. (unsigned long int) failed[idx_malloc],
  704. (unsigned long int) calls[idx_realloc],
  705. (unsigned long long int) total[idx_realloc],
  706. failed[idx_realloc] ? "\e[01;41m" : "",
  707. (unsigned long int) failed[idx_realloc],
  708. (unsigned long int) inplace,
  709. (unsigned long int) decreasing,
  710. (unsigned long int) realloc_free,
  711. (unsigned long int) calls[idx_calloc],
  712. (unsigned long long int) total[idx_calloc],
  713. failed[idx_calloc] ? "\e[01;41m" : "",
  714. (unsigned long int) failed[idx_calloc],
  715. (unsigned long int) calls[idx_free],
  716. (unsigned long long int) total[idx_free]);
  717. if (trace_mmap)
  718. fprintf (stderr, "\
  719. \e[00;34mmmap(r)|\e[0m %10lu %12llu %s%12lu\e[00;00m\n\
  720. \e[00;34mmmap(w)|\e[0m %10lu %12llu %s%12lu\e[00;00m\n\
  721. \e[00;34mmmap(a)|\e[0m %10lu %12llu %s%12lu\e[00;00m\n\
  722. \e[00;34m mremap|\e[0m %10lu %12llu %s%12lu\e[00;00m (nomove: %ld, dec:%ld)\n\
  723. \e[00;34m munmap|\e[0m %10lu %12llu %s%12lu\e[00;00m\n",
  724. (unsigned long int) calls[idx_mmap_r],
  725. (unsigned long long int) total[idx_mmap_r],
  726. failed[idx_mmap_r] ? "\e[01;41m" : "",
  727. (unsigned long int) failed[idx_mmap_r],
  728. (unsigned long int) calls[idx_mmap_w],
  729. (unsigned long long int) total[idx_mmap_w],
  730. failed[idx_mmap_w] ? "\e[01;41m" : "",
  731. (unsigned long int) failed[idx_mmap_w],
  732. (unsigned long int) calls[idx_mmap_a],
  733. (unsigned long long int) total[idx_mmap_a],
  734. failed[idx_mmap_a] ? "\e[01;41m" : "",
  735. (unsigned long int) failed[idx_mmap_a],
  736. (unsigned long int) calls[idx_mremap],
  737. (unsigned long long int) total[idx_mremap],
  738. failed[idx_mremap] ? "\e[01;41m" : "",
  739. (unsigned long int) failed[idx_mremap],
  740. (unsigned long int) inplace_mremap,
  741. (unsigned long int) decreasing_mremap,
  742. (unsigned long int) calls[idx_munmap],
  743. (unsigned long long int) total[idx_munmap],
  744. failed[idx_munmap] ? "\e[01;41m" : "",
  745. (unsigned long int) failed[idx_munmap]);
  746. /* Write out a histoogram of the sizes of the allocations. */
  747. fprintf (stderr, "\e[01;32mHistogram for block sizes:\e[0;0m\n");
  748. /* Determine the maximum of all calls for each size range. */
  749. maxcalls = large;
  750. for (cnt = 0; cnt < 65536; cnt += 16)
  751. if (histogram[cnt / 16] > maxcalls)
  752. maxcalls = histogram[cnt / 16];
  753. for (cnt = 0; cnt < 65536; cnt += 16)
  754. /* Only write out the nonzero entries. */
  755. if (histogram[cnt / 16] != 0)
  756. {
  757. percent = (histogram[cnt / 16] * 100) / calls_total;
  758. fprintf (stderr, "%5d-%-5d%12lu ", cnt, cnt + 15,
  759. (unsigned long int) histogram[cnt / 16]);
  760. if (percent == 0)
  761. fputs (" <1% \e[41;37m", stderr);
  762. else
  763. fprintf (stderr, "%3d%% \e[41;37m", percent);
  764. /* Draw a bar with a length corresponding to the current
  765. percentage. */
  766. percent = (histogram[cnt / 16] * 50) / maxcalls;
  767. while (percent-- > 0)
  768. fputc ('=', stderr);
  769. fputs ("\e[0;0m\n", stderr);
  770. }
  771. if (large != 0)
  772. {
  773. percent = (large * 100) / calls_total;
  774. fprintf (stderr, " large %12lu ", (unsigned long int) large);
  775. if (percent == 0)
  776. fputs (" <1% \e[41;37m", stderr);
  777. else
  778. fprintf (stderr, "%3d%% \e[41;37m", percent);
  779. percent = (large * 50) / maxcalls;
  780. while (percent-- > 0)
  781. fputc ('=', stderr);
  782. fputs ("\e[0;0m\n", stderr);
  783. }
  784. /* Any following malloc/free etc. calls should generate statistics again,
  785. because otherwise freeing something that has been malloced before
  786. this destructor (including struct header in front of it) wouldn't
  787. be properly freed. */
  788. not_me = false;
  789. }