1 /* Profile heap and stack memory usage of running program.
2 Copyright (C) 1998, 1999 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public License as
8 published by the Free Software Foundation; either version 2 of the
9 License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
31 /* Pointer to the real functions. These are determined used `dlsym'
32 when really needed. */
33 static void *(*mallocp
) (size_t);
34 static void *(*reallocp
) (void *, size_t);
35 static void *(*callocp
) (size_t, size_t);
36 static void (*freep
) (void *);
54 #define MAGIC 0xfeedbeaf
57 static unsigned long int calls
[idx_last
];
58 static unsigned long int failed
[idx_last
];
59 static unsigned long long int total
[idx_last
];
60 static unsigned long long int grand_total
;
61 static unsigned long int histogram
[65536 / 16];
62 static unsigned long int large
;
63 static unsigned long int calls_total
;
64 static unsigned long int inplace
;
65 static unsigned long int decreasing
;
66 static long int current_use
[2];
67 static long int peak_use
[3];
68 static uintptr_t start_sp
;
70 /* A few macros to make the source more readable. */
71 #define current_heap current_use[0]
72 #define current_stack current_use[1]
73 #define peak_heap peak_use[0]
74 #define peak_stack peak_use[1]
75 #define peak_total peak_use[2]
78 # define GETSP() ({ register uintptr_t stack_ptr asm ("esp"); stack_ptr; })
81 # define GETSP() ({ register uintptr_t stack_ptr asm ("$30"); stack_ptr; })
84 # define GETSP() ({ register uintptr_t stack_ptr asm ("%sp"); stack_ptr; })
87 # define GETSP() ({ register uintptr_t stack_ptr asm ("%r1"); stack_ptr; })
91 # define GETTIME(low,high) asm ("rdtsc" : "=a" (low), "=d" (high))
94 # define GETTIME(low,high) \
96 struct timeval tval; \
98 gettimeofday (&tval, NULL); \
99 usecs = (uint64_t) tval.tv_usec + (uint64_t) tval.tv_usec * 1000000; \
100 low = usecs & 0xffffffff; \
101 high = usecs >> 32; \
105 #define DEFAULT_BUFFER_SIZE 1024
106 static size_t buffer_size
;
111 extern const char *__progname
;
121 static struct entry buffer
[DEFAULT_BUFFER_SIZE
];
122 static size_t buffer_cnt
;
123 static struct entry first
;
126 /* Update the global data after a successful function call. */
128 update_data (struct header
*result
, size_t len
, size_t old_len
)
134 /* Record the information we need and mark the block using a
136 result
->length
= len
;
137 result
->magic
= MAGIC
;
140 /* Compute current heap usage and compare it with the maximum value. */
141 current_heap
+= len
- old_len
;
142 if (current_heap
> peak_heap
)
143 peak_heap
= current_heap
;
145 /* Compute current stack usage and compare it with the maximum value. */
146 current_stack
= start_sp
- GETSP ();
147 if (current_stack
> peak_stack
)
148 peak_stack
= current_stack
;
150 /* Add up heap and stack usage and compare it with the maximum value. */
151 total_use
= current_heap
+ current_stack
;
152 if (total_use
> peak_total
)
153 peak_total
= total_use
;
155 /* Store the value only if we are writing to a file. */
158 buffer
[buffer_cnt
].heap
= current_heap
;
159 buffer
[buffer_cnt
].stack
= current_stack
;
160 GETTIME (buffer
[buffer_cnt
].time_low
, buffer
[buffer_cnt
].time_high
);
163 /* Write out buffer if it is full. */
164 if (buffer_cnt
== buffer_size
)
166 write (fd
, buffer
, buffer_cnt
* sizeof (struct entry
));
173 /* Interrupt handler. */
175 int_handler (int signo
)
177 /* Nothing gets allocated. Just record the stack pointer position. */
178 update_data (NULL
, 0, 0);
182 /* Record the initial stack position. */
184 __attribute__ ((constructor
))
191 /* Find out whether this is the program we are supposed to profile.
192 For this the name in the variable `__progname' must match the one
193 given in the environment variable MEMPROF_PROG_NAME. If the variable
194 is not present every program assumes it should be profiling.
196 If this is the program open a file descriptor to the output file.
197 We will write to it whenever the buffer overflows. The name of the
198 output file is determined by the environment variable MEMPROF_OUTPUT.
200 If the environment variable MEMPROF_BUFFER_SIZE is set its numerical
201 value determines the size of the internal buffer. The number gives
202 the number of elements in the buffer. By setting the number to one
203 one effectively selects unbuffered operation.
205 If MEMPROF_NO_TIMER is not present an alarm handler is installed
206 which at the highest possible frequency records the stack pointer. */
210 const char *env
= getenv ("MEMPROF_PROG_NAME");
211 size_t prog_len
= strlen (__progname
);
214 /* Check for program name. */
215 size_t len
= strlen (env
);
216 if (len
> prog_len
|| strcmp (env
, &__progname
[prog_len
- len
]) != 0
217 || (prog_len
!= len
&& __progname
[prog_len
- len
- 1] != '/'))
221 /* Only open the file if it's really us. */
222 if (!not_me
&& fd
== -1)
224 const char *outname
= getenv ("MEMPROF_OUTPUT");
227 fd
= creat (outname
, 0666);
230 /* Don't do anything in future calls if we cannot write to
235 /* Write the first entry. */
238 GETTIME (first
.time_low
, first
.time_high
);
239 /* Write it two times since we need the starting and end time. */
240 write (fd
, &first
, sizeof (first
));
242 /* Determine the buffer size. We use the default if the
243 environment variable is not present. */
244 buffer_size
= DEFAULT_BUFFER_SIZE
;
245 if (getenv ("MEMPROF_BUFFER_SIZE") != NULL
)
247 buffer_size
= atoi (getenv ("MEMPROF_BUFFER_SIZE"));
248 if (buffer_size
== 0 || buffer_size
> DEFAULT_BUFFER_SIZE
)
249 buffer_size
= DEFAULT_BUFFER_SIZE
;
252 /* Possibly enable timer-based stack pointer retrieval. */
253 if (getenv ("MEMPROF_NO_TIMER") == NULL
)
255 struct sigaction act
;
257 act
.sa_handler
= (sighandler_t
) &int_handler
;
258 act
.sa_flags
= SA_RESTART
;
259 sigfillset (&act
.sa_mask
);
261 if (sigaction (SIGPROF
, &act
, NULL
) >= 0)
263 struct itimerval timer
;
265 timer
.it_value
.tv_sec
= 0;
266 timer
.it_value
.tv_usec
= 1;
267 timer
.it_interval
= timer
.it_value
;
268 setitimer (ITIMER_PROF
, &timer
, NULL
);
277 /* `malloc' replacement. We keep track of the memory usage if this is the
282 struct header
*result
= NULL
;
284 /* Determine real implementation if not already happened. */
288 mallocp
= (void *(*) (size_t)) dlsym (RTLD_NEXT
, "malloc");
291 /* If this is not the correct program just use the normal function. */
293 return (*mallocp
) (len
);
295 /* Keep track of number of calls. */
297 /* Keep track of total memory consumption for `malloc'. */
298 total
[idx_malloc
] += len
;
299 /* Keep track of total memory requirement. */
301 /* Remember the size of the request. */
303 ++histogram
[len
/ 16];
306 /* Total number of calls of any of the functions. */
309 /* Do the real work. */
310 result
= (struct header
*) (*mallocp
) (len
+ sizeof (struct header
));
313 ++failed
[idx_malloc
];
315 /* Update the allocation data and write out the records if necessary. */
316 update_data (result
, len
, 0);
318 /* Return the pointer to the user buffer. */
319 return result
? (void *) (result
+ 1) : NULL
;
323 /* `realloc' replacement. We keep track of the memory usage if this is the
326 realloc (void *old
, size_t len
)
328 struct header
*result
= NULL
;
332 /* Determine real implementation if not already happened. */
333 if (reallocp
== NULL
)
336 reallocp
= (void *(*) (void *, size_t)) dlsym (RTLD_NEXT
, "realloc");
339 /* If this is not the correct program just use the normal function. */
341 return (*reallocp
) (old
, len
);
345 /* This is really a `malloc' call. */
351 real
= ((struct header
*) old
) - 1;
352 if (real
->magic
!= MAGIC
)
353 /* This is no memory allocated here. */
354 return (*reallocp
) (old
, len
);
355 old_len
= real
->length
;
358 /* Keep track of number of calls. */
359 ++calls
[idx_realloc
];
360 /* Keep track of total memory consumption for `realloc'. */
361 total
[idx_realloc
] += len
;
362 /* Keep track of total memory requirement. */
364 /* Remember the size of the request. */
366 ++histogram
[len
/ 16];
369 /* Total number of calls of any of the functions. */
372 /* Do the real work. */
373 result
= (struct header
*) (*reallocp
) (real
, len
+ sizeof (struct header
));
376 ++failed
[idx_realloc
];
379 /* Record whether the reduction/increase happened in place. */
382 /* Was the buffer increased? */
386 /* Update the allocation data and write out the records if necessary. */
387 update_data (result
, len
, old_len
);
390 /* Return the pointer to the user buffer. */
391 return result
? (void *) (result
+ 1) : NULL
;
395 /* `calloc' replacement. We keep track of the memory usage if this is the
398 calloc (size_t n
, size_t len
)
400 struct header
*result
;
401 size_t size
= n
* len
;
403 /* Determine real implementation if not already happened. We are
404 searching for the `malloc' implementation since it is not always
405 efficiently possible to use `calloc' because we have to add a bit
406 room to the allocation to put the header in. */
410 mallocp
= (void *(*) (size_t)) dlsym (RTLD_NEXT
, "malloc");
413 /* If this is not the correct program just use the normal function. */
416 callocp
= (void *(*) (size_t, size_t)) dlsym (RTLD_NEXT
, "calloc");
418 return (*callocp
) (n
, len
);
421 /* Keep track of number of calls. */
423 /* Keep track of total memory consumption for `calloc'. */
424 total
[idx_calloc
] += size
;
425 /* Keep track of total memory requirement. */
427 /* Remember the size of the request. */
429 ++histogram
[size
/ 16];
432 /* Total number of calls of any of the functions. */
435 /* Do the real work. */
436 result
= (struct header
*) (*mallocp
) (size
+ sizeof (struct header
));
438 memset (result
+ 1, '\0', size
);
441 ++failed
[idx_calloc
];
443 /* Update the allocation data and write out the records if necessary. */
444 update_data (result
, size
, 0);
446 /* Return the pointer to the user buffer. */
447 return result
? (void *) (result
+ 1) : NULL
;
451 /* `free' replacement. We keep track of the memory usage if this is the
458 /* `free (NULL)' has no effect. */
465 /* Determine real implementation if not already happened. */
469 freep
= (void (*) (void *)) dlsym (RTLD_NEXT
, "free");
472 /* If this is not the correct program just use the normal function. */
479 /* Determine the pointer to the header. */
480 real
= ((struct header
*) ptr
) - 1;
481 if (real
->magic
!= MAGIC
)
483 /* This block wasn't allocated here. */
488 /* Keep track of number of calls. */
490 /* Keep track of total memory freed using `free'. */
491 total
[idx_free
] += real
->length
;
493 /* Update the allocation data and write out the records if necessary. */
494 update_data (NULL
, 0, real
->length
);
496 /* Do the real work. */
501 /* Write some statistics to standard error. */
503 __attribute__ ((destructor
))
507 unsigned long int maxcalls
;
509 /* If we haven't done anything here just return. */
512 /* If we should call any of the memory functions don't do any profiling. */
515 /* Finish the output file. */
518 /* Write the partially filled buffer. */
519 write (fd
, buffer
, buffer_cnt
* sizeof (struct entry
));
520 /* Go back to the beginning of the file. We allocated two records
521 here when we opened the file. */
522 lseek (fd
, 0, SEEK_SET
);
523 /* Write out a record containing the total size. */
524 first
.stack
= peak_total
;
525 write (fd
, &first
, sizeof (struct entry
));
526 /* Write out another record containing the maximum for heap and
528 first
.heap
= peak_heap
;
529 first
.stack
= peak_stack
;
530 GETTIME (first
.time_low
, first
.time_high
);
531 write (fd
, &first
, sizeof (struct entry
));
533 /* Close the file. */
538 /* Write a colorful statistic. */
539 fprintf (stderr
, "\n\
540 \e[01;32mMemory usage summary:\e[0;0m heap total: %llu, heap peak: %lu, stack peak: %lu\n\
541 \e[04;34m total calls total memory failed calls\e[0m\n\
542 \e[00;34m malloc|\e[0m %10lu %12llu %s%12lu\e[00;00m\n\
543 \e[00;34mrealloc|\e[0m %10lu %12llu %s%12lu\e[00;00m (in place: %ld, dec: %ld)\n\
544 \e[00;34m calloc|\e[0m %10lu %12llu %s%12lu\e[00;00m\n\
545 \e[00;34m free|\e[0m %10lu %12llu\n",
546 grand_total
, (unsigned long int) peak_heap
,
547 (unsigned long int) peak_stack
,
548 calls
[idx_malloc
], total
[idx_malloc
],
549 failed
[idx_malloc
] ? "\e[01;41m" : "", failed
[idx_malloc
],
550 calls
[idx_realloc
], total
[idx_realloc
],
551 failed
[idx_realloc
] ? "\e[01;41m" : "", failed
[idx_realloc
],
553 calls
[idx_calloc
], total
[idx_calloc
],
554 failed
[idx_calloc
] ? "\e[01;41m" : "", failed
[idx_calloc
],
555 calls
[idx_free
], total
[idx_free
]);
557 /* Write out a histoogram of the sizes of the allocations. */
558 fprintf (stderr
, "\e[01;32mHistogram for block sizes:\e[0;0m\n");
560 /* Determine the maximum of all calls for each size range. */
562 for (cnt
= 0; cnt
< 65536; cnt
+= 16)
563 if (histogram
[cnt
/ 16] > maxcalls
)
564 maxcalls
= histogram
[cnt
/ 16];
566 for (cnt
= 0; cnt
< 65536; cnt
+= 16)
567 /* Only write out the nonzero entries. */
568 if (histogram
[cnt
/ 16] != 0)
570 percent
= (histogram
[cnt
/ 16] * 100) / calls_total
;
571 fprintf (stderr
, "%5d-%-5d%12lu ", cnt
, cnt
+ 15,
572 histogram
[cnt
/ 16]);
574 fputs (" <1% \e[41;37m", stderr
);
576 fprintf (stderr
, "%3d%% \e[41;37m", percent
);
578 /* Draw a bar with a length corresponding to the current
580 percent
= (histogram
[cnt
/ 16] * 50) / maxcalls
;
581 while (percent
-- > 0)
583 fputs ("\e[0;0m\n", stderr
);
588 percent
= (large
* 100) / calls_total
;
589 fprintf (stderr
, " large %12lu ", large
);
591 fputs (" <1% \e[41;37m", stderr
);
593 fprintf (stderr
, "%3d%% \e[41;37m", percent
);
594 percent
= (large
* 50) / maxcalls
;
595 while (percent
-- > 0)
597 fputs ("\e[0;0m\n", stderr
);