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, gettext ("%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 higest
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, gettext ("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, gettext ("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, gettext ("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, gettext ("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, gettext ("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, gettext ("while closing '%s'"), fname);
309
310 error (0, 0, gettext ("%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 gettext ("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 (gettext (" (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 /* Ignore all sections which are not used at runtime. */
432 if ((shdr->sh_flags & SHF_ALLOC) != 0)
433 {
434 printf ((radix == radix_hex
435 ? "%-*s %*" PRIx64 " %*" PRIx64 "\n"
436 : (radix == radix_decimal
437 ? "%-*s %*" PRId64 " %*" PRId64 "\n"
438 : "%-*s %*" PRIo64 " %*" PRIo64 "\n")),
439 maxlen, elf_strptr (elf, shstrndx, shdr->sh_name),
440 digits - 2, shdr->sh_size,
441 digits, shdr->sh_addr);
442
443 total += shdr->sh_size;
444 }
445 }
446
447 if (radix == radix_hex)
448 printf ("%-*s %*" PRIx64 "\n\n\n", maxlen, sgettext ("sysv|Total"),
449 digits - 2, total);
450 else if (radix == radix_decimal)
451 printf ("%-*s %*" PRId64 "\n\n\n", maxlen, sgettext ("sysv|Total"),
452 digits - 2, total);
453 else
454 printf ("%-*s %*" PRIo64 "\n\n\n", maxlen, sgettext ("sysv|Total"),
455 digits - 2, total);
456 }
457
458
459 /* Show sizes in SysV format in one line. */
460 static void
show_sysv_one_line(Elf * elf)461 show_sysv_one_line (Elf *elf)
462 {
463 /* Get the section header string table index. */
464 size_t shstrndx;
465 if (unlikely (elf_getshdrstrndx (elf, &shstrndx) < 0))
466 error (EXIT_FAILURE, 0,
467 gettext ("cannot get section header string table index"));
468
469 /* Iterate over all sections. */
470 GElf_Off total = 0;
471 bool first = true;
472 Elf_Scn *scn = NULL;
473 while ((scn = elf_nextscn (elf, scn)) != NULL)
474 {
475 GElf_Shdr shdr_mem;
476 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
477
478 /* Ignore all sections which are not used at runtime. */
479 if ((shdr->sh_flags & SHF_ALLOC) == 0)
480 continue;
481
482 if (! first)
483 fputs_unlocked (" + ", stdout);
484 first = false;
485
486 printf ((radix == radix_hex ? "%" PRIx64 "(%s)"
487 : (radix == radix_decimal ? "%" PRId64 "(%s)"
488 : "%" PRIo64 "(%s)")),
489 shdr->sh_size, elf_strptr (elf, shstrndx, shdr->sh_name));
490
491 total += shdr->sh_size;
492 }
493
494 if (radix == radix_hex)
495 printf (" = %#" PRIx64 "\n", total);
496 else if (radix == radix_decimal)
497 printf (" = %" PRId64 "\n", total);
498 else
499 printf (" = %" PRIo64 "\n", total);
500 }
501
502
503 /* Variables to add up the sizes of all files. */
504 static uintmax_t total_textsize;
505 static uintmax_t total_datasize;
506 static uintmax_t total_bsssize;
507
508
509 /* Show sizes in BSD format. */
510 static void
show_bsd(Elf * elf,const char * prefix,const char * fname,const char * fullname)511 show_bsd (Elf *elf, const char *prefix, const char *fname,
512 const char *fullname)
513 {
514 GElf_Off textsize = 0;
515 GElf_Off datasize = 0;
516 GElf_Off bsssize = 0;
517 const int ddigits = length_map[gelf_getclass (elf) - 1][radix_decimal];
518 const int xdigits = length_map[gelf_getclass (elf) - 1][radix_hex];
519
520 /* Iterate over all sections. */
521 Elf_Scn *scn = NULL;
522 while ((scn = elf_nextscn (elf, scn)) != NULL)
523 {
524 GElf_Shdr shdr_mem;
525 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
526
527 if (shdr == NULL)
528 INTERNAL_ERROR (fullname);
529
530 /* Ignore all sections which are not marked as loaded. */
531 if ((shdr->sh_flags & SHF_ALLOC) == 0)
532 continue;
533
534 if ((shdr->sh_flags & SHF_WRITE) == 0)
535 textsize += shdr->sh_size;
536 else if (shdr->sh_type == SHT_NOBITS)
537 bsssize += shdr->sh_size;
538 else
539 datasize += shdr->sh_size;
540 }
541
542 printf ("%*" PRId64 " %*" PRId64 " %*" PRId64 " %*" PRId64 " %*"
543 PRIx64 " %s",
544 ddigits - 2, textsize,
545 ddigits - 2, datasize,
546 ddigits - 2, bsssize,
547 ddigits - 2, textsize + datasize + bsssize,
548 xdigits - 2, textsize + datasize + bsssize,
549 fname);
550 if (prefix != NULL)
551 printf (gettext (" (ex %s)"), prefix);
552 fputs_unlocked ("\n", stdout);
553
554 total_textsize += textsize;
555 total_datasize += datasize;
556 total_bsssize += bsssize;
557
558 totals_class = MAX (totals_class, gelf_getclass (elf));
559 }
560
561
562 /* Show total size. */
563 static void
show_bsd_totals(void)564 show_bsd_totals (void)
565 {
566 int ddigits = length_map[totals_class - 1][radix_decimal];
567 int xdigits = length_map[totals_class - 1][radix_hex];
568
569 printf ("%*" PRIuMAX " %*" PRIuMAX " %*" PRIuMAX " %*" PRIuMAX " %*"
570 PRIxMAX " %s",
571 ddigits - 2, total_textsize,
572 ddigits - 2, total_datasize,
573 ddigits - 2, total_bsssize,
574 ddigits - 2, total_textsize + total_datasize + total_bsssize,
575 xdigits - 2, total_textsize + total_datasize + total_bsssize,
576 gettext ("(TOTALS)\n"));
577 }
578
579
580 /* Show size and permission of loadable segments. */
581 static void
show_segments(Elf * elf,const char * fullname)582 show_segments (Elf *elf, const char *fullname)
583 {
584 size_t phnum;
585 if (elf_getphdrnum (elf, &phnum) != 0)
586 INTERNAL_ERROR (fullname);
587
588 GElf_Off total = 0;
589 bool first = true;
590 for (size_t cnt = 0; cnt < phnum; ++cnt)
591 {
592 GElf_Phdr phdr_mem;
593 GElf_Phdr *phdr;
594
595 phdr = gelf_getphdr (elf, cnt, &phdr_mem);
596 if (phdr == NULL)
597 INTERNAL_ERROR (fullname);
598
599 if (phdr->p_type != PT_LOAD)
600 /* Only load segments. */
601 continue;
602
603 if (! first)
604 fputs_unlocked (" + ", stdout);
605 first = false;
606
607 printf (radix == radix_hex ? "%" PRIx64 "(%c%c%c)"
608 : (radix == radix_decimal ? "%" PRId64 "(%c%c%c)"
609 : "%" PRIo64 "(%c%c%c)"),
610 phdr->p_memsz,
611 (phdr->p_flags & PF_R) == 0 ? '-' : 'r',
612 (phdr->p_flags & PF_W) == 0 ? '-' : 'w',
613 (phdr->p_flags & PF_X) == 0 ? '-' : 'x');
614
615 total += phdr->p_memsz;
616 }
617
618 if (radix == radix_hex)
619 printf (" = %#" PRIx64 "\n", total);
620 else if (radix == radix_decimal)
621 printf (" = %" PRId64 "\n", total);
622 else
623 printf (" = %" PRIo64 "\n", total);
624 }
625
626
627 static void
handle_elf(Elf * elf,const char * prefix,const char * fname)628 handle_elf (Elf *elf, const char *prefix, const char *fname)
629 {
630 size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
631 size_t fname_len = strlen (fname) + 1;
632 char fullname[prefix_len + 1 + fname_len];
633 char *cp = fullname;
634
635 /* Create the full name of the file. */
636 if (prefix != NULL)
637 {
638 cp = mempcpy (cp, prefix, prefix_len);
639 *cp++ = ':';
640 }
641 memcpy (cp, fname, fname_len);
642
643 if (format == format_sysv)
644 show_sysv (elf, prefix, fname, fullname);
645 else if (format == format_sysv_one_line)
646 show_sysv_one_line (elf);
647 else if (format == format_segments)
648 show_segments (elf, fullname);
649 else
650 {
651 print_header (elf);
652
653 show_bsd (elf, prefix, fname, fullname);
654 }
655 }
656
657
658 #include "debugpred.h"
659