1 /* Generate graphic from memory profiling data.
2    Copyright (C) 1998-2022 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4 
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published
7    by the Free Software Foundation; version 2 of the License, or
8    (at your option) any later version.
9 
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, see <https://www.gnu.org/licenses/>.  */
17 
18 #define _FILE_OFFSET_BITS 64
19 
20 #include <argp.h>
21 #include <assert.h>
22 #include <errno.h>
23 #include <error.h>
24 #include <fcntl.h>
25 #include <getopt.h>
26 #include <inttypes.h>
27 #include <libintl.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <stdint.h>
33 #include <sys/param.h>
34 #include <sys/stat.h>
35 
36 #include <gd.h>
37 #include <gdfontl.h>
38 #include <gdfonts.h>
39 
40 #include "../version.h"
41 #define PACKAGE _libc_intl_domainname
42 
43 /* Default size of the generated image.  */
44 #define XSIZE 800
45 #define YSIZE 600
46 
47 #ifndef N_
48 # define N_(Arg) Arg
49 #endif
50 
51 
52 /* Definitions of arguments for argp functions.  */
53 static const struct argp_option options[] =
54 {
55   { "output", 'o', N_ ("FILE"), 0, N_ ("Name output file") },
56   { "string", 's', N_ ("STRING"), 0, N_ ("Title string used in output graphic") },
57   { "time", 't', NULL, 0, N_ ("\
58 Generate output linear to time (default is linear to number of function calls)\
59 ") },
60   { "total", 'T', NULL, 0,
61     N_ ("Also draw graph for total memory consumption") },
62   { "x-size", 'x', N_ ("VALUE"), 0,
63     N_ ("Make output graphic VALUE pixels wide") },
64   { "y-size", 'y', "VALUE", 0, N_ ("Make output graphic VALUE pixels high") },
65   { NULL, 0, NULL, 0, NULL }
66 };
67 
68 /* Short description of program.  */
69 static const char doc[] = N_ ("Generate graphic from memory profiling data");
70 
71 /* Strings for arguments in help texts.  */
72 static const char args_doc[] = N_ ("DATAFILE [OUTFILE]");
73 
74 /* Prototype for option handler.  */
75 static error_t parse_opt (int key, char *arg, struct argp_state *state);
76 
77 /* Function to print some extra text in the help message.  */
78 static char *more_help (int key, const char *text, void *input);
79 
80 /* Name and version of program.  */
81 static void print_version (FILE *stream, struct argp_state *state);
82 void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
83 
84 /* Data structure to communicate with argp functions.  */
85 static struct argp argp =
86 {
87   options, parse_opt, args_doc, doc, NULL, more_help
88 };
89 
90 
91 struct entry
92 {
93   uint64_t heap;
94   uint64_t stack;
95   uint32_t time_low;
96   uint32_t time_high;
97 };
98 
99 
100 /* Size of the image.  */
101 static size_t xsize;
102 static size_t ysize;
103 
104 /* Name of the output file.  */
105 static char *outname;
106 
107 /* Title string for the graphic.  */
108 static const char *string;
109 
110 /* Nonzero if graph should be generated linear in time.  */
111 static int time_based;
112 
113 /* Nonzero if graph to display total use of memory should be drawn as well.  */
114 static int also_total = 0;
115 
116 
117 int
main(int argc,char * argv[])118 main (int argc, char *argv[])
119 {
120   int remaining;
121   const char *inname;
122   gdImagePtr im_out;
123   int grey, blue, red, green, yellow, black;
124   int fd;
125   struct stat st;
126   size_t maxsize_heap;
127   size_t maxsize_stack;
128   size_t maxsize_total;
129   uint64_t total;
130   uint64_t cnt, cnt2;
131   FILE *outfile;
132   char buf[30];
133   size_t last_heap;
134   size_t last_stack;
135   size_t last_total;
136   struct entry headent[2];
137   uint64_t start_time;
138   uint64_t end_time;
139   uint64_t total_time;
140   const char *heap_format, *stack_format;
141   int heap_scale, stack_scale, line;
142 
143   outname = NULL;
144   xsize = XSIZE;
145   ysize = YSIZE;
146   string = NULL;
147 
148   /* Parse and process arguments.  */
149   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
150 
151   if (remaining >= argc || remaining + 2 < argc)
152     {
153       argp_help (&argp, stdout, ARGP_HELP_SEE | ARGP_HELP_EXIT_ERR,
154                  program_invocation_short_name);
155       exit (1);
156     }
157 
158   inname = argv[remaining++];
159 
160   if (remaining < argc)
161     outname = argv[remaining];
162   else if (outname == NULL)
163     {
164       size_t len = strlen (inname);
165       outname = alloca (len + 5);
166       stpcpy (stpcpy (outname, inname), ".png");
167     }
168 
169   /* Open for read/write since we try to repair the file in case the
170      application hasn't terminated cleanly.  */
171   fd = open (inname, O_RDWR);
172   if (fd == -1)
173     error (EXIT_FAILURE, errno, "cannot open input file");
174   if (fstat (fd, &st) != 0)
175     {
176       close (fd);
177       error (EXIT_FAILURE, errno, "cannot get size of input file");
178     }
179   /* Test whether the file contains only full records.  */
180   if ((st.st_size % sizeof (struct entry)) != 0
181       /* The file must at least contain the two administrative records.  */
182       || st.st_size < 2 * sizeof (struct entry))
183     {
184       close (fd);
185       error (EXIT_FAILURE, 0, "input file has incorrect size");
186     }
187   /* Compute number of data entries.  */
188   total = st.st_size / sizeof (struct entry) - 2;
189 
190   /* Read the administrative information.  */
191   read (fd, headent, sizeof (headent));
192   maxsize_heap = headent[1].heap;
193   maxsize_stack = headent[1].stack;
194   maxsize_total = headent[0].stack;
195 
196   if (maxsize_heap == 0 && maxsize_stack == 0)
197     {
198       /* The program aborted before memusage was able to write the
199          information about the maximum heap and stack use.  Repair
200          the file now.  */
201       struct entry next;
202 
203       while (1)
204         {
205           if (read (fd, &next, sizeof (next)) == 0)
206             break;
207           if (next.heap > maxsize_heap)
208             maxsize_heap = next.heap;
209           if (next.stack > maxsize_stack)
210             maxsize_stack = next.stack;
211           if (maxsize_heap + maxsize_stack > maxsize_total)
212             maxsize_total = maxsize_heap + maxsize_stack;
213         }
214 
215       headent[0].stack = maxsize_total;
216       headent[1].heap = maxsize_heap;
217       headent[1].stack = maxsize_stack;
218       headent[1].time_low = next.time_low;
219       headent[1].time_high = next.time_high;
220 
221       /* Write the computed values in the file.  */
222       lseek (fd, 0, SEEK_SET);
223       write (fd, headent, 2 * sizeof (struct entry));
224     }
225 
226   if (also_total)
227     {
228       /* We use one scale and since we also draw the total amount of
229          memory used we have to adapt the maximum.  */
230       maxsize_heap = maxsize_total;
231       maxsize_stack = maxsize_total;
232     }
233 
234   start_time = ((uint64_t) headent[0].time_high) << 32 | headent[0].time_low;
235   end_time = ((uint64_t) headent[1].time_high) << 32 | headent[1].time_low;
236   total_time = end_time - start_time;
237 
238   if (xsize < 100)
239     xsize = 100;
240   if (ysize < 80)
241     ysize = 80;
242 
243   /* Create output image with the specified size.  */
244   im_out = gdImageCreate (xsize, ysize);
245 
246   /* First color allocated is background.  */
247   grey = gdImageColorAllocate (im_out, 224, 224, 224);
248 
249   /* Set transparent color. */
250   gdImageColorTransparent (im_out, grey);
251 
252   /* These are all the other colors we need (in the moment).  */
253   red = gdImageColorAllocate (im_out, 255, 0, 0);
254   green = gdImageColorAllocate (im_out, 0, 130, 0);
255   blue = gdImageColorAllocate (im_out, 0, 0, 255);
256   yellow = gdImageColorAllocate (im_out, 154, 205, 50);
257   black = gdImageColorAllocate (im_out, 0, 0, 0);
258 
259   gdImageRectangle (im_out, 40, 20, xsize - 40, ysize - 20, blue);
260 
261   if (maxsize_heap < 1024)
262     {
263       heap_format = "%Zu";
264       heap_scale = 1;
265     }
266   else if (maxsize_heap < 1024 * 1024 * 100)
267     {
268       heap_format = "%Zuk";
269       heap_scale = 1024;
270     }
271   else
272     {
273       heap_format = "%ZuM";
274       heap_scale = 1024 * 1024;
275     }
276 
277   if (maxsize_stack < 1024)
278     {
279       stack_format = "%Zu";
280       stack_scale = 1;
281     }
282   else if (maxsize_stack < 1024 * 1024 * 100)
283     {
284       stack_format = "%Zuk";
285       stack_scale = 1024;
286     }
287   else
288     {
289       stack_format = "%ZuM";
290       stack_scale = 1024 * 1024;
291     }
292 
293   gdImageString (im_out, gdFontSmall, 38, ysize - 14, (unsigned char *) "0",
294                  blue);
295   snprintf (buf, sizeof (buf), heap_format, 0);
296   gdImageString (im_out, gdFontSmall, maxsize_heap < 1024 ? 32 : 26,
297                  ysize - 26, (unsigned char *) buf, red);
298   snprintf (buf, sizeof (buf), stack_format, 0);
299   gdImageString (im_out, gdFontSmall, xsize - 37, ysize - 26,
300                  (unsigned char *) buf, green);
301 
302   if (string != NULL)
303     gdImageString (im_out, gdFontLarge, (xsize - strlen (string) * 8) / 2,
304                    2, (unsigned char *) string, green);
305 
306   gdImageStringUp (im_out, gdFontSmall, 1, ysize / 2 - 10,
307                    (unsigned char *) "allocated", red);
308   gdImageStringUp (im_out, gdFontSmall, 11, ysize / 2 - 10,
309                    (unsigned char *) "memory", red);
310 
311   gdImageStringUp (im_out, gdFontSmall, xsize - 39, ysize / 2 - 10,
312                    (unsigned char *) "used", green);
313   gdImageStringUp (im_out, gdFontSmall, xsize - 27, ysize / 2 - 10,
314                    (unsigned char *) "stack", green);
315 
316   snprintf (buf, sizeof (buf), heap_format, maxsize_heap / heap_scale);
317   gdImageString (im_out, gdFontSmall, 39 - strlen (buf) * 6, 14,
318                  (unsigned char *) buf, red);
319   snprintf (buf, sizeof (buf), stack_format, maxsize_stack / stack_scale);
320   gdImageString (im_out, gdFontSmall, xsize - 37, 14,
321                  (unsigned char *) buf, green);
322 
323   for (line = 1; line <= 3; ++line)
324     {
325       if (maxsize_heap > 0)
326         {
327           cnt = (((ysize - 40) * (maxsize_heap / 4 * line / heap_scale))
328                  / (maxsize_heap / heap_scale));
329           gdImageDashedLine (im_out, 40, ysize - 20 - cnt, xsize - 40,
330                              ysize - 20 - cnt, red);
331           snprintf (buf, sizeof (buf), heap_format,
332                     maxsize_heap / 4 * line / heap_scale);
333           gdImageString (im_out, gdFontSmall, 39 - strlen (buf) * 6,
334                          ysize - 26 - cnt, (unsigned char *) buf, red);
335         }
336       else
337         cnt = 0;
338 
339       if (maxsize_stack > 0)
340         cnt2 = (((ysize - 40) * (maxsize_stack / 4 * line / stack_scale))
341                 / (maxsize_stack / stack_scale));
342       else
343         cnt2 = 0;
344 
345       if (cnt != cnt2)
346         gdImageDashedLine (im_out, 40, ysize - 20 - cnt2, xsize - 40,
347                            ysize - 20 - cnt2, green);
348       snprintf (buf, sizeof (buf), stack_format,
349 		maxsize_stack / 4 * line / stack_scale);
350       gdImageString (im_out, gdFontSmall, xsize - 37, ysize - 26 - cnt2,
351                      (unsigned char *) buf, green);
352     }
353 
354   snprintf (buf, sizeof (buf), "%llu", (unsigned long long) total);
355   gdImageString (im_out, gdFontSmall, xsize - 50, ysize - 14,
356                  (unsigned char *) buf, blue);
357 
358   if (!time_based)
359     {
360       uint64_t previously = start_time;
361 
362       gdImageString (im_out, gdFontSmall, 40 + (xsize - 32 * 6 - 80) / 2,
363                      ysize - 12,
364                      (unsigned char *) "# memory handling function calls",
365                      blue);
366 
367 
368       last_stack = last_heap = last_total = ysize - 20;
369       for (cnt = 1; cnt <= total; ++cnt)
370         {
371           struct entry entry;
372           size_t new[2];
373           uint64_t now;
374 
375           read (fd, &entry, sizeof (entry));
376 
377           now = ((uint64_t) entry.time_high) << 32 | entry.time_low;
378 
379           if ((((previously - start_time) * 100) / total_time) % 10 < 5)
380             gdImageFilledRectangle (im_out,
381                                     40 + ((cnt - 1) * (xsize - 80)) / total,
382                                     ysize - 19,
383                                     39 + (cnt * (xsize - 80)) / total,
384                                     ysize - 14, yellow);
385           previously = now;
386 
387           if (also_total && maxsize_heap > 0)
388             {
389               size_t new3;
390 
391               new3 = (ysize - 20) - ((((unsigned long long int) (ysize - 40))
392                                       * (entry.heap + entry.stack))
393                                      / maxsize_heap);
394               gdImageLine (im_out, 40 + ((xsize - 80) * (cnt - 1)) / total,
395                            last_total,
396                            40 + ((xsize - 80) * cnt) / total, new3,
397                            black);
398               last_total = new3;
399             }
400 
401           if (maxsize_heap > 0)
402             {
403               new[0] = ((ysize - 20)
404                         - ((((unsigned long long int) (ysize - 40))
405                             * entry.heap) / maxsize_heap));
406               gdImageLine (im_out, 40 + ((xsize - 80) * (cnt - 1)) / total,
407                            last_heap, 40 + ((xsize - 80) * cnt) / total,
408                            new[0], red);
409               last_heap = new[0];
410             }
411 
412           if (maxsize_stack > 0)
413             {
414               new[1] = ((ysize - 20)
415                         - ((((unsigned long long int) (ysize - 40))
416                             * entry.stack) / maxsize_stack));
417               gdImageLine (im_out, 40 + ((xsize - 80) * (cnt - 1)) / total,
418                            last_stack, 40 + ((xsize - 80) * cnt) / total,
419                            new[1], green);
420               last_stack = new[1];
421             }
422         }
423 
424       cnt = 0;
425       while (cnt < total)
426         {
427           gdImageLine (im_out, 40 + ((xsize - 80) * cnt) / total, ysize - 20,
428                        40 + ((xsize - 80) * cnt) / total, ysize - 15, blue);
429           cnt += MAX (1, total / 20);
430         }
431       gdImageLine (im_out, xsize - 40, ysize - 20, xsize - 40, ysize - 15,
432                    blue);
433     }
434   else
435     {
436       uint64_t next_tick = MAX (1, total / 20);
437       size_t last_xpos = 40;
438 
439       gdImageString (im_out, gdFontSmall, 40 + (xsize - 39 * 6 - 80) / 2,
440                      ysize - 12,
441                      (unsigned char *) "				      \
442 # memory handling function calls / time", blue);
443 
444       for (cnt = 0; cnt < 20; cnt += 2)
445         gdImageFilledRectangle (im_out,
446                                 40 + (cnt * (xsize - 80)) / 20, ysize - 19,
447                                 39 + ((cnt + 1) * (xsize - 80)) / 20,
448                                 ysize - 14, yellow);
449 
450       last_stack = last_heap = last_total = ysize - 20;
451       for (cnt = 1; cnt <= total; ++cnt)
452         {
453           struct entry entry;
454           size_t new[2];
455           size_t xpos;
456           uint64_t now;
457 
458           read (fd, &entry, sizeof (entry));
459 
460           now = ((uint64_t) entry.time_high) << 32 | entry.time_low;
461           xpos = 40 + ((xsize - 80) * (now - start_time)) / total_time;
462 
463           if (cnt == next_tick)
464             {
465               gdImageLine (im_out, xpos, ysize - 20, xpos, ysize - 15, blue);
466               next_tick += MAX (1, total / 20);
467             }
468 
469           if (also_total && maxsize_heap > 0)
470             {
471               size_t new3;
472 
473               new3 = (ysize - 20) - ((((unsigned long long int) (ysize - 40))
474                                       * (entry.heap + entry.stack))
475                                      / maxsize_heap);
476               gdImageLine (im_out, last_xpos, last_total, xpos, new3, black);
477               last_total = new3;
478             }
479 
480           if (maxsize_heap > 0)
481             {
482               new[0] = ((ysize - 20)
483                         - ((((unsigned long long int) (ysize - 40))
484                             * entry.heap) / maxsize_heap));
485               gdImageLine (im_out, last_xpos, last_heap, xpos, new[0], red);
486               last_heap = new[0];
487             }
488 
489           if (maxsize_stack > 0)
490             {
491               new[1] = ((ysize - 20)
492                         - ((((unsigned long long int) (ysize - 40))
493                             * entry.stack) / maxsize_stack));
494               gdImageLine (im_out, last_xpos, last_stack, xpos, new[1],
495                            green);
496               last_stack = new[1];
497             }
498 
499           last_xpos = xpos;
500         }
501     }
502 
503   /* Write out the result.  */
504   outfile = fopen (outname, "w");
505   if (outfile == NULL)
506     error (EXIT_FAILURE, errno, "cannot open output file");
507 
508   gdImagePng (im_out, outfile);
509 
510   fclose (outfile);
511 
512   gdImageDestroy (im_out);
513 
514   return 0;
515 }
516 
517 
518 /* Handle program arguments.  */
519 static error_t
parse_opt(int key,char * arg,struct argp_state * state)520 parse_opt (int key, char *arg, struct argp_state *state)
521 {
522   switch (key)
523     {
524     case 'o':
525       outname = arg;
526       break;
527     case 's':
528       string = arg;
529       break;
530     case 't':
531       time_based = 1;
532       break;
533     case 'T':
534       also_total = 1;
535       break;
536     case 'x':
537       xsize = atoi (arg);
538       if (xsize == 0)
539         xsize = XSIZE;
540       break;
541     case 'y':
542       ysize = atoi (arg);
543       if (ysize == 0)
544         ysize = XSIZE;
545       break;
546     default:
547       return ARGP_ERR_UNKNOWN;
548     }
549   return 0;
550 }
551 
552 
553 static char *
more_help(int key,const char * text,void * input)554 more_help (int key, const char *text, void *input)
555 {
556   char *tp;
557 
558   switch (key)
559     {
560     case ARGP_KEY_HELP_EXTRA:
561       /* We print some extra information.  */
562       if (asprintf (&tp, gettext ("\
563 For bug reporting instructions, please see:\n\
564 %s.\n"), REPORT_BUGS_TO) < 0)
565         return NULL;
566 
567       return tp;
568 
569     default:
570       break;
571     }
572   return (char *) text;
573 }
574 
575 /* Print the version information.  */
576 static void
print_version(FILE * stream,struct argp_state * state)577 print_version (FILE *stream, struct argp_state *state)
578 {
579   fprintf (stream, "memusagestat %s%s\n", PKGVERSION, VERSION);
580   fprintf (stream, gettext ("\
581 Copyright (C) %s Free Software Foundation, Inc.\n\
582 This is free software; see the source for copying conditions.  There is NO\n\
583 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
584 "), "2022");
585   fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
586 }
587