• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Print size information from ELF file.
2    Copyright (C) 2000-2007,2009,2012,2014,2015 Red Hat, Inc.
3    This file is part of elfutils.
4    Written by Ulrich Drepper <drepper@redhat.com>, 2000.
5 
6    This file is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10 
11    elfutils is distributed in the hope that it will be useful, but
12    WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15 
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18 
19 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
22 
23 #include <argp.h>
24 #include <fcntl.h>
25 #include <gelf.h>
26 #include <inttypes.h>
27 #include <libelf.h>
28 #include <libintl.h>
29 #include <locale.h>
30 #include <stdbool.h>
31 #include <stdio.h>
32 #include <stdio_ext.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 
37 #include <system.h>
38 #include <printversion.h>
39 
40 /* Name and version of program.  */
41 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
42 
43 /* Bug report address.  */
44 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
45 
46 
47 /* Values for the parameters which have no short form.  */
48 #define OPT_FORMAT	0x100
49 #define OPT_RADIX	0x101
50 
51 /* Definitions of arguments for argp functions.  */
52 static const struct argp_option options[] =
53 {
54   { NULL, 0, NULL, 0, N_("Output format:"), 0 },
55   { "format", OPT_FORMAT, "FORMAT", 0,
56     N_("Use the output format FORMAT.  FORMAT can be `bsd' or `sysv'.  "
57        "The default is `bsd'"), 0 },
58   { NULL, 'A', NULL, 0, N_("Same as `--format=sysv'"), 0 },
59   { NULL, 'B', NULL, 0, N_("Same as `--format=bsd'"), 0 },
60   { "radix", OPT_RADIX, "RADIX", 0, N_("Use RADIX for printing symbol values"),
61     0},
62   { NULL, 'd', NULL, 0, N_("Same as `--radix=10'"), 0 },
63   { NULL, 'o', NULL, 0, N_("Same as `--radix=8'"), 0 },
64   { NULL, 'x', NULL, 0, N_("Same as `--radix=16'"), 0 },
65   { NULL, 'f', NULL, 0,
66     N_("Similar to `--format=sysv' output but in one line"), 0 },
67 
68   { NULL, 0, NULL, 0, N_("Output options:"), 0 },
69   { NULL, 'F', NULL, 0,
70     N_("Print size and permission flags for loadable segments"), 0 },
71   { "totals", 't', NULL, 0, N_("Display the total sizes (bsd only)"), 0 },
72   { NULL, 0, NULL, 0, NULL, 0 }
73 };
74 
75 /* Short description of program.  */
76 static const char doc[] = N_("\
77 List section sizes of FILEs (a.out by default).");
78 
79 /* Strings for arguments in help texts.  */
80 static const char args_doc[] = N_("[FILE...]");
81 
82 /* Prototype for option handler.  */
83 static error_t parse_opt (int key, char *arg, struct argp_state *state);
84 
85 /* Data structure to communicate with argp functions.  */
86 static struct argp argp =
87 {
88   options, parse_opt, args_doc, doc, NULL, NULL, NULL
89 };
90 
91 
92 /* Print symbols in file named FNAME.  */
93 static int process_file (const char *fname);
94 
95 /* Handle content of archive.  */
96 static int handle_ar (int fd, Elf *elf, const char *prefix, const char *fname);
97 
98 /* Handle ELF file.  */
99 static void handle_elf (Elf *elf, const char *fullname, const char *fname);
100 
101 /* Show total size.  */
102 static void show_bsd_totals (void);
103 
104 #define INTERNAL_ERROR(fname) \
105   error (EXIT_FAILURE, 0, _("%s: INTERNAL ERROR %d (%s): %s"),      \
106 	 fname, __LINE__, PACKAGE_VERSION, elf_errmsg (-1))
107 
108 
109 /* User-selectable options.  */
110 
111 /* The selected output format.  */
112 static enum
113 {
114   format_bsd = 0,
115   format_sysv,
116   format_sysv_one_line,
117   format_segments
118 } format;
119 
120 /* Radix for printed numbers.  */
121 static enum
122 {
123   radix_decimal = 0,
124   radix_hex,
125   radix_octal
126 } radix;
127 
128 
129 /* Mapping of radix and binary class to length.  */
130 static const int length_map[2][3] =
131 {
132   [ELFCLASS32 - 1] =
133   {
134     [radix_hex] = 8,
135     [radix_decimal] = 10,
136     [radix_octal] = 11
137   },
138   [ELFCLASS64 - 1] =
139   {
140     [radix_hex] = 16,
141     [radix_decimal] = 20,
142     [radix_octal] = 22
143   }
144 };
145 
146 /* True if total sizes should be printed.  */
147 static bool totals;
148 /* To print the total sizes in a reasonable format remember the highest
149    "class" of ELF binaries processed.  */
150 static int totals_class;
151 
152 
153 int
main(int argc,char * argv[])154 main (int argc, char *argv[])
155 {
156   int remaining;
157   int result = 0;
158 
159   /* We use no threads here which can interfere with handling a stream.  */
160   __fsetlocking (stdin, FSETLOCKING_BYCALLER);
161   __fsetlocking (stdout, FSETLOCKING_BYCALLER);
162   __fsetlocking (stderr, FSETLOCKING_BYCALLER);
163 
164   /* Set locale.  */
165   setlocale (LC_ALL, "");
166 
167   /* Make sure the message catalog can be found.  */
168   bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
169 
170   /* Initialize the message catalog.  */
171   textdomain (PACKAGE_TARNAME);
172 
173   /* Parse and process arguments.  */
174   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
175 
176 
177   /* Tell the library which version we are expecting.  */
178   elf_version (EV_CURRENT);
179 
180   if (remaining == argc)
181     /* The user didn't specify a name so we use a.out.  */
182     result = process_file ("a.out");
183   else
184     /* Process all the remaining files.  */
185     do
186       result |= process_file (argv[remaining]);
187     while (++remaining < argc);
188 
189   /* Print the total sizes but only if the output format is BSD and at
190      least one file has been correctly read (i.e., we recognized the
191      class).  */
192   if (totals && format == format_bsd && totals_class != 0)
193     show_bsd_totals ();
194 
195   return result;
196 }
197 
198 
199 /* Handle program arguments.  */
200 static error_t
parse_opt(int key,char * arg,struct argp_state * state)201 parse_opt (int key, char *arg,
202 	   struct argp_state *state __attribute__ ((unused)))
203 {
204   switch (key)
205     {
206     case 'd':
207       radix = radix_decimal;
208       break;
209 
210     case 'f':
211       format = format_sysv_one_line;
212       break;
213 
214     case 'o':
215       radix = radix_octal;
216       break;
217 
218     case 'x':
219       radix = radix_hex;
220       break;
221 
222     case 'A':
223       format = format_sysv;
224       break;
225 
226     case 'B':
227       format = format_bsd;
228       break;
229 
230     case 'F':
231       format = format_segments;
232       break;
233 
234     case OPT_FORMAT:
235       if (strcmp (arg, "bsd") == 0 || strcmp (arg, "berkeley") == 0)
236 	format = format_bsd;
237       else if (likely (strcmp (arg, "sysv") == 0))
238 	format = format_sysv;
239       else
240 	error (EXIT_FAILURE, 0, _("Invalid format: %s"), arg);
241       break;
242 
243     case OPT_RADIX:
244       if (strcmp (arg, "x") == 0 || strcmp (arg, "16") == 0)
245 	radix = radix_hex;
246       else if (strcmp (arg, "d") == 0 || strcmp (arg, "10") == 0)
247 	radix = radix_decimal;
248       else if (strcmp (arg, "o") == 0 || strcmp (arg, "8") == 0)
249 	radix = radix_octal;
250       else
251 	error (EXIT_FAILURE, 0, _("Invalid radix: %s"), arg);
252       break;
253 
254     case 't':
255       totals = true;
256       break;
257 
258     default:
259       return ARGP_ERR_UNKNOWN;
260     }
261   return 0;
262 }
263 
264 
265 /* Open the file and determine the type.  */
266 static int
process_file(const char * fname)267 process_file (const char *fname)
268 {
269   int fd = open (fname, O_RDONLY);
270   if (unlikely (fd == -1))
271     {
272       error (0, errno, _("cannot open '%s'"), fname);
273       return 1;
274     }
275 
276   /* Now get the ELF descriptor.  */
277   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
278   if (likely (elf != NULL))
279     {
280       if (elf_kind (elf) == ELF_K_ELF)
281 	{
282 	  handle_elf (elf, NULL, fname);
283 
284 	  if (unlikely (elf_end (elf) != 0))
285 	    INTERNAL_ERROR (fname);
286 
287 	  if (unlikely (close (fd) != 0))
288 	    error (EXIT_FAILURE, errno, _("while closing '%s'"), fname);
289 
290 	  return 0;
291 	}
292       else if (likely (elf_kind (elf) == ELF_K_AR))
293 	{
294 	  int result = handle_ar (fd, elf, NULL, fname);
295 
296 	  if (unlikely  (close (fd) != 0))
297 	    error (EXIT_FAILURE, errno, _("while closing '%s'"), fname);
298 
299 	  return result;
300 	}
301 
302       /* We cannot handle this type.  Close the descriptor anyway.  */
303       if (unlikely (elf_end (elf) != 0))
304 	INTERNAL_ERROR (fname);
305     }
306 
307   if (unlikely (close (fd) != 0))
308     error (EXIT_FAILURE, errno, _("while closing '%s'"), fname);
309 
310   error (0, 0, _("%s: file format not recognized"), fname);
311 
312   return 1;
313 }
314 
315 
316 /* Print the BSD-style header.  This is done exactly once.  */
317 static void
print_header(Elf * elf)318 print_header (Elf *elf)
319 {
320   static int done;
321 
322   if (! done)
323     {
324       int ddigits = length_map[gelf_getclass (elf) - 1][radix_decimal];
325       int xdigits = length_map[gelf_getclass (elf) - 1][radix_hex];
326 
327       printf ("%*s %*s %*s %*s %*s %s\n",
328 	      ddigits - 2, sgettext ("bsd|text"),
329 	      ddigits - 2, sgettext ("bsd|data"),
330 	      ddigits - 2, sgettext ("bsd|bss"),
331 	      ddigits - 2, sgettext ("bsd|dec"),
332 	      xdigits - 2, sgettext ("bsd|hex"),
333 	      sgettext ("bsd|filename"));
334 
335       done = 1;
336     }
337 }
338 
339 
340 static int
handle_ar(int fd,Elf * elf,const char * prefix,const char * fname)341 handle_ar (int fd, Elf *elf, const char *prefix, const char *fname)
342 {
343   size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
344   size_t fname_len = strlen (fname) + 1;
345   char new_prefix[prefix_len + 1 + fname_len];
346   char *cp = new_prefix;
347 
348   /* Create the full name of the file.  */
349   if (prefix != NULL)
350     {
351       cp = mempcpy (cp, prefix, prefix_len);
352       *cp++ = ':';
353     }
354   memcpy (cp, fname, fname_len);
355 
356   /* Process all the files contained in the archive.  */
357   int result = 0;
358   Elf *subelf;
359   Elf_Cmd cmd = ELF_C_READ_MMAP;
360   while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
361     {
362       /* The the header for this element.  */
363       Elf_Arhdr *arhdr = elf_getarhdr (subelf);
364 
365       if (elf_kind (subelf) == ELF_K_ELF)
366 	handle_elf (subelf, new_prefix, arhdr->ar_name);
367       else if (likely (elf_kind (subelf) == ELF_K_AR))
368 	result |= handle_ar (fd, subelf, new_prefix, arhdr->ar_name);
369       /* else signal error??? */
370 
371       /* Get next archive element.  */
372       cmd = elf_next (subelf);
373       if (unlikely (elf_end (subelf) != 0))
374 	INTERNAL_ERROR (fname);
375     }
376 
377   /* Only close ELF handle if this was a "top level" ar file.  */
378   if (prefix == NULL)
379     if (unlikely (elf_end (elf) != 0))
380       INTERNAL_ERROR (fname);
381 
382   return result;
383 }
384 
385 
386 /* Show sizes in SysV format.  */
387 static void
show_sysv(Elf * elf,const char * prefix,const char * fname,const char * fullname)388 show_sysv (Elf *elf, const char *prefix, const char *fname,
389 	   const char *fullname)
390 {
391   int maxlen = 10;
392   const int digits = length_map[gelf_getclass (elf) - 1][radix];
393 
394   /* Get the section header string table index.  */
395   size_t shstrndx;
396   if (unlikely (elf_getshdrstrndx (elf, &shstrndx) < 0))
397     error (EXIT_FAILURE, 0,
398 	   _("cannot get section header string table index"));
399 
400   /* First round over the sections: determine the longest section name.  */
401   Elf_Scn *scn = NULL;
402   while ((scn = elf_nextscn (elf, scn)) != NULL)
403     {
404       GElf_Shdr shdr_mem;
405       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
406 
407       if (shdr == NULL)
408 	INTERNAL_ERROR (fullname);
409 
410       /* Ignore all sections which are not used at runtime.  */
411       const char *name = elf_strptr (elf, shstrndx, shdr->sh_name);
412       if (name != NULL && (shdr->sh_flags & SHF_ALLOC) != 0)
413 	maxlen = MAX (maxlen, (int) strlen (name));
414     }
415 
416   fputs_unlocked (fname, stdout);
417   if (prefix != NULL)
418     printf (_(" (ex %s)"), prefix);
419   printf (":\n%-*s %*s %*s\n",
420 	  maxlen, sgettext ("sysv|section"),
421 	  digits - 2, sgettext ("sysv|size"),
422 	  digits, sgettext ("sysv|addr"));
423 
424   /* Iterate over all sections.  */
425   GElf_Off total = 0;
426   while ((scn = elf_nextscn (elf, scn)) != NULL)
427     {
428       GElf_Shdr shdr_mem;
429       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
430 
431       if (shdr == NULL)
432 	INTERNAL_ERROR (fullname);
433 
434       /* Ignore all sections which are not used at runtime.  */
435       if ((shdr->sh_flags & SHF_ALLOC) != 0)
436 	{
437 	  printf ((radix == radix_hex
438 		   ? "%-*s %*" PRIx64 " %*" PRIx64 "\n"
439 		   : (radix == radix_decimal
440 		      ? "%-*s %*" PRId64 " %*" PRId64 "\n"
441 		      : "%-*s %*" PRIo64 " %*" PRIo64 "\n")),
442 		  maxlen, elf_strptr (elf, shstrndx, shdr->sh_name),
443 		  digits - 2, shdr->sh_size,
444 		  digits, shdr->sh_addr);
445 
446 	  total += shdr->sh_size;
447 	}
448     }
449 
450   if (radix == radix_hex)
451     printf ("%-*s %*" PRIx64 "\n\n\n", maxlen, sgettext ("sysv|Total"),
452 	    digits - 2, total);
453   else if (radix == radix_decimal)
454     printf ("%-*s %*" PRId64 "\n\n\n", maxlen, sgettext ("sysv|Total"),
455 	    digits - 2, total);
456   else
457     printf ("%-*s %*" PRIo64 "\n\n\n", maxlen, sgettext ("sysv|Total"),
458 	    digits - 2, total);
459 }
460 
461 
462 /* Show sizes in SysV format in one line.  */
463 static void
show_sysv_one_line(Elf * elf)464 show_sysv_one_line (Elf *elf)
465 {
466   /* Get the section header string table index.  */
467   size_t shstrndx;
468   if (unlikely (elf_getshdrstrndx (elf, &shstrndx) < 0))
469     error (EXIT_FAILURE, 0,
470 	   _("cannot get section header string table index"));
471 
472   /* Iterate over all sections.  */
473   GElf_Off total = 0;
474   bool first = true;
475   Elf_Scn *scn = NULL;
476   while ((scn = elf_nextscn (elf, scn)) != NULL)
477     {
478       GElf_Shdr shdr_mem;
479       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
480 
481       if (unlikely (shdr == NULL))
482 	error (EXIT_FAILURE, 0, _("cannot get section header"));
483 
484       /* Ignore all sections which are not used at runtime.  */
485       if ((shdr->sh_flags & SHF_ALLOC) == 0)
486 	continue;
487 
488       if (! first)
489 	fputs_unlocked (" + ", stdout);
490       first = false;
491 
492       printf ((radix == radix_hex ? "%" PRIx64 "(%s)"
493 	       : (radix == radix_decimal ? "%" PRId64 "(%s)"
494 		  : "%" PRIo64 "(%s)")),
495 	      shdr->sh_size, elf_strptr (elf, shstrndx, shdr->sh_name));
496 
497       total += shdr->sh_size;
498     }
499 
500   if (radix == radix_hex)
501     printf (" = %#" PRIx64 "\n", total);
502   else if (radix == radix_decimal)
503     printf (" = %" PRId64 "\n", total);
504   else
505     printf (" = %" PRIo64 "\n", total);
506 }
507 
508 
509 /* Variables to add up the sizes of all files.  */
510 static uintmax_t total_textsize;
511 static uintmax_t total_datasize;
512 static uintmax_t total_bsssize;
513 
514 
515 /* Show sizes in BSD format.  */
516 static void
show_bsd(Elf * elf,const char * prefix,const char * fname,const char * fullname)517 show_bsd (Elf *elf, const char *prefix, const char *fname,
518 	  const char *fullname)
519 {
520   GElf_Off textsize = 0;
521   GElf_Off datasize = 0;
522   GElf_Off bsssize = 0;
523   const int ddigits = length_map[gelf_getclass (elf) - 1][radix_decimal];
524   const int xdigits = length_map[gelf_getclass (elf) - 1][radix_hex];
525 
526   /* Iterate over all sections.  */
527   Elf_Scn *scn = NULL;
528   while ((scn = elf_nextscn (elf, scn)) != NULL)
529     {
530       GElf_Shdr shdr_mem;
531       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
532 
533       if (shdr == NULL)
534 	INTERNAL_ERROR (fullname);
535 
536       /* Ignore all sections which are not marked as loaded.  */
537       if ((shdr->sh_flags & SHF_ALLOC) == 0)
538 	continue;
539 
540       if ((shdr->sh_flags & SHF_WRITE) == 0)
541 	textsize += shdr->sh_size;
542       else if (shdr->sh_type == SHT_NOBITS)
543 	bsssize += shdr->sh_size;
544       else
545 	datasize += shdr->sh_size;
546     }
547 
548   printf (radix == radix_decimal
549           ? "%*" PRId64 " %*" PRId64 " %*" PRId64 " %*" PRId64 " %*" PRIx64 " %s"
550 	  : radix == radix_hex
551 	  ? "%#*" PRIx64 " %#*" PRIx64 " %#*" PRIx64 " %*" PRId64 " %*" PRIx64 " %s"
552 	  : "%#*" PRIo64 " %#*" PRIo64 " %#*" PRIo64 " %*" PRId64 " %*" PRIx64 " %s",
553 	  ddigits - 2, textsize,
554 	  ddigits - 2, datasize,
555 	  ddigits - 2, bsssize,
556 	  ddigits - 2, textsize + datasize + bsssize,
557 	  xdigits - 2, textsize + datasize + bsssize,
558 	  fname);
559   if (prefix != NULL)
560     printf (_(" (ex %s)"), prefix);
561   fputs_unlocked ("\n", stdout);
562 
563   total_textsize += textsize;
564   total_datasize += datasize;
565   total_bsssize += bsssize;
566 
567   totals_class = MAX (totals_class, gelf_getclass (elf));
568 }
569 
570 
571 /* Show total size.  */
572 static void
show_bsd_totals(void)573 show_bsd_totals (void)
574 {
575   int ddigits = length_map[totals_class - 1][radix_decimal];
576   int xdigits = length_map[totals_class - 1][radix_hex];
577 
578   printf ("%*" PRIuMAX " %*" PRIuMAX " %*" PRIuMAX " %*" PRIuMAX " %*"
579 	  PRIxMAX " %s",
580 	  ddigits - 2, total_textsize,
581 	  ddigits - 2, total_datasize,
582 	  ddigits - 2, total_bsssize,
583 	  ddigits - 2, total_textsize + total_datasize + total_bsssize,
584 	  xdigits - 2, total_textsize + total_datasize + total_bsssize,
585 	  _("(TOTALS)\n"));
586 }
587 
588 
589 /* Show size and permission of loadable segments.  */
590 static void
show_segments(Elf * elf,const char * fullname)591 show_segments (Elf *elf, const char *fullname)
592 {
593   size_t phnum;
594   if (elf_getphdrnum (elf, &phnum) != 0)
595     INTERNAL_ERROR (fullname);
596 
597   GElf_Off total = 0;
598   bool first = true;
599   for (size_t cnt = 0; cnt < phnum; ++cnt)
600     {
601       GElf_Phdr phdr_mem;
602       GElf_Phdr *phdr;
603 
604       phdr = gelf_getphdr (elf, cnt, &phdr_mem);
605       if (phdr == NULL)
606 	INTERNAL_ERROR (fullname);
607 
608       if (phdr->p_type != PT_LOAD)
609 	/* Only load segments.  */
610 	continue;
611 
612       if (! first)
613 	fputs_unlocked (" + ", stdout);
614       first = false;
615 
616       printf (radix == radix_hex ? "%" PRIx64 "(%c%c%c)"
617 	      : (radix == radix_decimal ? "%" PRId64 "(%c%c%c)"
618 		 : "%" PRIo64 "(%c%c%c)"),
619 	      phdr->p_memsz,
620 	      (phdr->p_flags & PF_R) == 0 ? '-' : 'r',
621 	      (phdr->p_flags & PF_W) == 0 ? '-' : 'w',
622 	      (phdr->p_flags & PF_X) == 0 ? '-' : 'x');
623 
624       total += phdr->p_memsz;
625     }
626 
627   if (radix == radix_hex)
628     printf (" = %#" PRIx64 "\n", total);
629   else if (radix == radix_decimal)
630     printf (" = %" PRId64 "\n", total);
631   else
632     printf (" = %" PRIo64 "\n", total);
633 }
634 
635 
636 static void
handle_elf(Elf * elf,const char * prefix,const char * fname)637 handle_elf (Elf *elf, const char *prefix, const char *fname)
638 {
639   size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
640   size_t fname_len = strlen (fname) + 1;
641   char fullname[prefix_len + 1 + fname_len];
642   char *cp = fullname;
643 
644   /* Create the full name of the file.  */
645   if (prefix != NULL)
646     {
647       cp = mempcpy (cp, prefix, prefix_len);
648       *cp++ = ':';
649     }
650   memcpy (cp, fname, fname_len);
651 
652   if (format == format_sysv)
653     show_sysv (elf, prefix, fname, fullname);
654   else if (format == format_sysv_one_line)
655     show_sysv_one_line (elf);
656   else if (format == format_segments)
657     show_segments (elf, fullname);
658   else
659     {
660       print_header (elf);
661 
662       show_bsd (elf, prefix, fname, fullname);
663     }
664 }
665 
666 
667 #include "debugpred.h"
668