More fixes for invalid memory accesses triggered by fuzzed binaries.
[external/binutils.git] / binutils / size.c
1 /* size.c -- report size of various sections of an executable file.
2    Copyright (C) 1991-2015 Free Software Foundation, Inc.
3
4    This file is part of GNU Binutils.
5
6    This program 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    This program 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
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, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20 \f
21 /* Extensions/incompatibilities:
22    o - BSD output has filenames at the end.
23    o - BSD output can appear in different radicies.
24    o - SysV output has less redundant whitespace.  Filename comes at end.
25    o - SysV output doesn't show VMA which is always the same as the PMA.
26    o - We also handle core files.
27    o - We also handle archives.
28    If you write shell scripts which manipulate this info then you may be
29    out of luck; there's no --compatibility or --pedantic option.  */
30
31 #include "sysdep.h"
32 #include "bfd.h"
33 #include "libiberty.h"
34 #include "getopt.h"
35 #include "bucomm.h"
36
37 #ifndef BSD_DEFAULT
38 #define BSD_DEFAULT 1
39 #endif
40
41 /* Program options.  */
42
43 static enum
44   {
45     decimal, octal, hex
46   }
47 radix = decimal;
48
49 /* 0 means use AT&T-style output.  */
50 static int berkeley_format = BSD_DEFAULT;
51
52 static int show_version = 0;
53 static int show_help = 0;
54 static int show_totals = 0;
55 static int show_common = 0;
56
57 static bfd_size_type common_size;
58 static bfd_size_type total_bsssize;
59 static bfd_size_type total_datasize;
60 static bfd_size_type total_textsize;
61
62 /* Program exit status.  */
63 static int return_code = 0;
64
65 static char *target = NULL;
66
67 /* Forward declarations.  */
68
69 static void display_file (char *);
70 static void rprint_number (int, bfd_size_type);
71 static void print_sizes (bfd * file);
72 \f
73 static void
74 usage (FILE *stream, int status)
75 {
76   fprintf (stream, _("Usage: %s [option(s)] [file(s)]\n"), program_name);
77   fprintf (stream, _(" Displays the sizes of sections inside binary files\n"));
78   fprintf (stream, _(" If no input file(s) are specified, a.out is assumed\n"));
79   fprintf (stream, _(" The options are:\n\
80   -A|-B     --format={sysv|berkeley}  Select output style (default is %s)\n\
81   -o|-d|-x  --radix={8|10|16}         Display numbers in octal, decimal or hex\n\
82   -t        --totals                  Display the total sizes (Berkeley only)\n\
83             --common                  Display total size for *COM* syms\n\
84             --target=<bfdname>        Set the binary file format\n\
85             @<file>                   Read options from <file>\n\
86   -h        --help                    Display this information\n\
87   -v        --version                 Display the program's version\n\
88 \n"),
89 #if BSD_DEFAULT
90   "berkeley"
91 #else
92   "sysv"
93 #endif
94 );
95   list_supported_targets (program_name, stream);
96   if (REPORT_BUGS_TO[0] && status == 0)
97     fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
98   exit (status);
99 }
100
101 #define OPTION_FORMAT (200)
102 #define OPTION_RADIX (OPTION_FORMAT + 1)
103 #define OPTION_TARGET (OPTION_RADIX + 1)
104
105 static struct option long_options[] =
106 {
107   {"common", no_argument, &show_common, 1},
108   {"format", required_argument, 0, OPTION_FORMAT},
109   {"radix", required_argument, 0, OPTION_RADIX},
110   {"target", required_argument, 0, OPTION_TARGET},
111   {"totals", no_argument, &show_totals, 1},
112   {"version", no_argument, &show_version, 1},
113   {"help", no_argument, &show_help, 1},
114   {0, no_argument, 0, 0}
115 };
116
117 int main (int, char **);
118
119 int
120 main (int argc, char **argv)
121 {
122   int temp;
123   int c;
124
125 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
126   setlocale (LC_MESSAGES, "");
127 #endif
128 #if defined (HAVE_SETLOCALE)
129   setlocale (LC_CTYPE, "");
130 #endif
131   bindtextdomain (PACKAGE, LOCALEDIR);
132   textdomain (PACKAGE);
133
134   program_name = *argv;
135   xmalloc_set_program_name (program_name);
136
137   expandargv (&argc, &argv);
138
139   bfd_init ();
140   set_default_bfd_target ();
141
142   while ((c = getopt_long (argc, argv, "ABHhVvdfotx", long_options,
143                            (int *) 0)) != EOF)
144     switch (c)
145       {
146       case OPTION_FORMAT:
147         switch (*optarg)
148           {
149           case 'B':
150           case 'b':
151             berkeley_format = 1;
152             break;
153           case 'S':
154           case 's':
155             berkeley_format = 0;
156             break;
157           default:
158             non_fatal (_("invalid argument to --format: %s"), optarg);
159             usage (stderr, 1);
160           }
161         break;
162
163       case OPTION_TARGET:
164         target = optarg;
165         break;
166
167       case OPTION_RADIX:
168 #ifdef ANSI_LIBRARIES
169         temp = strtol (optarg, NULL, 10);
170 #else
171         temp = atol (optarg);
172 #endif
173         switch (temp)
174           {
175           case 10:
176             radix = decimal;
177             break;
178           case 8:
179             radix = octal;
180             break;
181           case 16:
182             radix = hex;
183             break;
184           default:
185             non_fatal (_("Invalid radix: %s\n"), optarg);
186             usage (stderr, 1);
187           }
188         break;
189
190       case 'A':
191         berkeley_format = 0;
192         break;
193       case 'B':
194         berkeley_format = 1;
195         break;
196       case 'v':
197       case 'V':
198         show_version = 1;
199         break;
200       case 'd':
201         radix = decimal;
202         break;
203       case 'x':
204         radix = hex;
205         break;
206       case 'o':
207         radix = octal;
208         break;
209       case 't':
210         show_totals = 1;
211         break;
212       case 'f': /* FIXME : For sysv68, `-f' means `full format', i.e.
213                    `[fname:] M(.text) + N(.data) + O(.bss) + P(.comment) = Q'
214                    where `fname: ' appears only if there are >= 2 input files,
215                    and M, N, O, P, Q are expressed in decimal by default,
216                    hexa or octal if requested by `-x' or `-o'.
217                    Just to make things interesting, Solaris also accepts -f,
218                    which prints out the size of each allocatable section, the
219                    name of the section, and the total of the section sizes.  */
220                 /* For the moment, accept `-f' silently, and ignore it.  */
221         break;
222       case 0:
223         break;
224       case 'h':
225       case 'H':
226       case '?':
227         usage (stderr, 1);
228       }
229
230   if (show_version)
231     print_version ("size");
232   if (show_help)
233     usage (stdout, 0);
234
235   if (optind == argc)
236     display_file ("a.out");
237   else
238     for (; optind < argc;)
239       display_file (argv[optind++]);
240
241   if (show_totals && berkeley_format)
242     {
243       bfd_size_type total = total_textsize + total_datasize + total_bsssize;
244
245       rprint_number (7, total_textsize);
246       putchar('\t');
247       rprint_number (7, total_datasize);
248       putchar('\t');
249       rprint_number (7, total_bsssize);
250       printf (((radix == octal) ? "\t%7lo\t%7lx\t" : "\t%7lu\t%7lx\t"),
251               (unsigned long) total, (unsigned long) total);
252       fputs ("(TOTALS)\n", stdout);
253     }
254
255   return return_code;
256 }
257 \f
258 /* Total size required for common symbols in ABFD.  */
259
260 static void
261 calculate_common_size (bfd *abfd)
262 {
263   asymbol **syms = NULL;
264   long storage, symcount;
265
266   common_size = 0;
267   if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC | HAS_SYMS)) != HAS_SYMS)
268     return;
269
270   storage = bfd_get_symtab_upper_bound (abfd);
271   if (storage < 0)
272     bfd_fatal (bfd_get_filename (abfd));
273   if (storage)
274     syms = (asymbol **) xmalloc (storage);
275
276   symcount = bfd_canonicalize_symtab (abfd, syms);
277   if (symcount < 0)
278     bfd_fatal (bfd_get_filename (abfd));
279
280   while (--symcount >= 0)
281     {
282       asymbol *sym = syms[symcount];
283
284       if (bfd_is_com_section (sym->section)
285           && (sym->flags & BSF_SECTION_SYM) == 0)
286         common_size += sym->value;
287     }
288   free (syms);
289 }
290
291 /* Display stats on file or archive member ABFD.  */
292
293 static void
294 display_bfd (bfd *abfd)
295 {
296   char **matching;
297
298   if (bfd_check_format (abfd, bfd_archive))
299     /* An archive within an archive.  */
300     return;
301
302   if (bfd_check_format_matches (abfd, bfd_object, &matching))
303     {
304       print_sizes (abfd);
305       printf ("\n");
306       return;
307     }
308
309   if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
310     {
311       bfd_nonfatal (bfd_get_filename (abfd));
312       list_matching_formats (matching);
313       free (matching);
314       return_code = 3;
315       return;
316     }
317
318   if (bfd_check_format_matches (abfd, bfd_core, &matching))
319     {
320       const char *core_cmd;
321
322       print_sizes (abfd);
323       fputs (" (core file", stdout);
324
325       core_cmd = bfd_core_file_failing_command (abfd);
326       if (core_cmd)
327         printf (" invoked as %s", core_cmd);
328
329       puts (")\n");
330       return;
331     }
332
333   bfd_nonfatal (bfd_get_filename (abfd));
334
335   if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
336     {
337       list_matching_formats (matching);
338       free (matching);
339     }
340
341   return_code = 3;
342 }
343
344 static void
345 display_archive (bfd *file)
346 {
347   bfd *arfile = (bfd *) NULL;
348   bfd *last_arfile = (bfd *) NULL;
349
350   for (;;)
351     {
352       bfd_set_error (bfd_error_no_error);
353
354       arfile = bfd_openr_next_archived_file (file, arfile);
355       if (arfile == NULL)
356         {
357           if (bfd_get_error () != bfd_error_no_more_archived_files)
358             {
359               bfd_nonfatal (bfd_get_filename (file));
360               return_code = 2;
361             }
362           break;
363         }
364
365       display_bfd (arfile);
366
367       if (last_arfile != NULL)
368         {
369           bfd_close (last_arfile);
370
371           /* PR 17512: file: a244edbc.  */
372           if (last_arfile == arfile)
373             return;
374         }
375
376       last_arfile = arfile;
377     }
378
379   if (last_arfile != NULL)
380     bfd_close (last_arfile);
381 }
382
383 static void
384 display_file (char *filename)
385 {
386   bfd *file;
387
388   if (get_file_size (filename) < 1)
389     {
390       return_code = 1;
391       return;
392     }
393
394   file = bfd_openr (filename, target);
395   if (file == NULL)
396     {
397       bfd_nonfatal (filename);
398       return_code = 1;
399       return;
400     }
401
402   if (bfd_check_format (file, bfd_archive))
403     display_archive (file);
404   else
405     display_bfd (file);
406
407   if (!bfd_close (file))
408     {
409       bfd_nonfatal (filename);
410       return_code = 1;
411       return;
412     }
413 }
414 \f
415 static int
416 size_number (bfd_size_type num)
417 {
418   char buffer[40];
419
420   sprintf (buffer,
421            (radix == decimal ? "%" BFD_VMA_FMT "u" :
422            ((radix == octal) ? "0%" BFD_VMA_FMT "o" : "0x%" BFD_VMA_FMT "x")),
423            num);
424
425   return strlen (buffer);
426 }
427
428 static void
429 rprint_number (int width, bfd_size_type num)
430 {
431   char buffer[40];
432
433   sprintf (buffer,
434            (radix == decimal ? "%" BFD_VMA_FMT "u" :
435            ((radix == octal) ? "0%" BFD_VMA_FMT "o" : "0x%" BFD_VMA_FMT "x")),
436            num);
437
438   printf ("%*s", width, buffer);
439 }
440
441 static bfd_size_type bsssize;
442 static bfd_size_type datasize;
443 static bfd_size_type textsize;
444
445 static void
446 berkeley_sum (bfd *abfd ATTRIBUTE_UNUSED, sec_ptr sec,
447               void *ignore ATTRIBUTE_UNUSED)
448 {
449   flagword flags;
450   bfd_size_type size;
451
452   flags = bfd_get_section_flags (abfd, sec);
453   if ((flags & SEC_ALLOC) == 0)
454     return;
455
456   size = bfd_get_section_size (sec);
457   if ((flags & SEC_CODE) != 0 || (flags & SEC_READONLY) != 0)
458     textsize += size;
459   else if ((flags & SEC_HAS_CONTENTS) != 0)
460     datasize += size;
461   else
462     bsssize += size;
463 }
464
465 static void
466 print_berkeley_format (bfd *abfd)
467 {
468   static int files_seen = 0;
469   bfd_size_type total;
470
471   bsssize = 0;
472   datasize = 0;
473   textsize = 0;
474
475   bfd_map_over_sections (abfd, berkeley_sum, NULL);
476
477   bsssize += common_size;
478   if (files_seen++ == 0)
479     puts ((radix == octal) ? "   text\t   data\t    bss\t    oct\t    hex\tfilename" :
480           "   text\t   data\t    bss\t    dec\t    hex\tfilename");
481
482   total = textsize + datasize + bsssize;
483
484   if (show_totals)
485     {
486       total_textsize += textsize;
487       total_datasize += datasize;
488       total_bsssize  += bsssize;
489     }
490
491   rprint_number (7, textsize);
492   putchar ('\t');
493   rprint_number (7, datasize);
494   putchar ('\t');
495   rprint_number (7, bsssize);
496   printf (((radix == octal) ? "\t%7lo\t%7lx\t" : "\t%7lu\t%7lx\t"),
497           (unsigned long) total, (unsigned long) total);
498
499   fputs (bfd_get_filename (abfd), stdout);
500
501   if (bfd_my_archive (abfd))
502     printf (" (ex %s)", bfd_get_filename (bfd_my_archive (abfd)));
503 }
504
505 /* I REALLY miss lexical functions! */
506 bfd_size_type svi_total = 0;
507 bfd_vma svi_maxvma = 0;
508 int svi_namelen = 0;
509 int svi_vmalen = 0;
510 int svi_sizelen = 0;
511
512 static void
513 sysv_internal_sizer (bfd *file ATTRIBUTE_UNUSED, sec_ptr sec,
514                      void *ignore ATTRIBUTE_UNUSED)
515 {
516   bfd_size_type size = bfd_section_size (file, sec);
517
518   if (   ! bfd_is_abs_section (sec)
519       && ! bfd_is_com_section (sec)
520       && ! bfd_is_und_section (sec))
521     {
522       int namelen = strlen (bfd_section_name (file, sec));
523
524       if (namelen > svi_namelen)
525         svi_namelen = namelen;
526
527       svi_total += size;
528
529       if (bfd_section_vma (file, sec) > svi_maxvma)
530         svi_maxvma = bfd_section_vma (file, sec);
531     }
532 }
533
534 static void
535 sysv_one_line (const char *name, bfd_size_type size, bfd_vma vma)
536 {
537   printf ("%-*s   ", svi_namelen, name);
538   rprint_number (svi_sizelen, size);
539   printf ("   ");
540   rprint_number (svi_vmalen, vma);
541   printf ("\n");
542 }
543
544 static void
545 sysv_internal_printer (bfd *file ATTRIBUTE_UNUSED, sec_ptr sec,
546                        void *ignore ATTRIBUTE_UNUSED)
547 {
548   bfd_size_type size = bfd_section_size (file, sec);
549
550   if (   ! bfd_is_abs_section (sec)
551       && ! bfd_is_com_section (sec)
552       && ! bfd_is_und_section (sec))
553     {
554       svi_total += size;
555
556       sysv_one_line (bfd_section_name (file, sec),
557                      size,
558                      bfd_section_vma (file, sec));
559     }
560 }
561
562 static void
563 print_sysv_format (bfd *file)
564 {
565   /* Size all of the columns.  */
566   svi_total = 0;
567   svi_maxvma = 0;
568   svi_namelen = 0;
569   bfd_map_over_sections (file, sysv_internal_sizer, NULL);
570   if (show_common)
571     {
572       if (svi_namelen < (int) sizeof ("*COM*") - 1)
573         svi_namelen = sizeof ("*COM*") - 1;
574       svi_total += common_size;
575     }
576
577   svi_vmalen = size_number ((bfd_size_type)svi_maxvma);
578
579   if ((size_t) svi_vmalen < sizeof ("addr") - 1)
580     svi_vmalen = sizeof ("addr")-1;
581
582   svi_sizelen = size_number (svi_total);
583   if ((size_t) svi_sizelen < sizeof ("size") - 1)
584     svi_sizelen = sizeof ("size")-1;
585
586   svi_total = 0;
587   printf ("%s  ", bfd_get_filename (file));
588
589   if (bfd_my_archive (file))
590     printf (" (ex %s)", bfd_get_filename (bfd_my_archive (file)));
591
592   printf (":\n%-*s   %*s   %*s\n", svi_namelen, "section",
593           svi_sizelen, "size", svi_vmalen, "addr");
594
595   bfd_map_over_sections (file, sysv_internal_printer, NULL);
596   if (show_common)
597     {
598       svi_total += common_size;
599       sysv_one_line ("*COM*", common_size, 0);
600     }
601
602   printf ("%-*s   ", svi_namelen, "Total");
603   rprint_number (svi_sizelen, svi_total);
604   printf ("\n\n");
605 }
606
607 static void
608 print_sizes (bfd *file)
609 {
610   if (show_common)
611     calculate_common_size (file);
612   if (berkeley_format)
613     print_berkeley_format (file);
614   else
615     print_sysv_format (file);
616 }