2 * Copyright (c) 2007 S.Sam Arun Raj
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 #include <capsicum_helpers.h>
40 #include <libcasper.h>
41 #include <casper/cap_fileargs.h>
45 ELFTC_VCSID("$Id: size.c 3458 2016-05-09 15:01:25Z emaste $");
48 #define ELF_ALIGN(val,x) (((val)+(x)-1) & ~((x)-1))
49 #define SIZE_VERSION_STRING "size 1.0"
68 static uint64_t bss_size, data_size, text_size, total_size;
69 static uint64_t bss_size_total, data_size_total, text_size_total;
70 static int show_totals;
71 static int size_option;
72 static enum radix_style radix = RADIX_DECIMAL;
73 static enum output_style style = STYLE_BERKELEY;
87 static struct option size_longopts[] = {
88 { "format", required_argument, &size_option, OPT_FORMAT },
89 { "help", no_argument, NULL, 'h' },
90 { "radix", required_argument, &size_option, OPT_RADIX },
91 { "totals", no_argument, NULL, 't' },
92 { "version", no_argument, NULL, 'V' },
96 static void berkeley_calc(GElf_Shdr *);
97 static void berkeley_footer(const char *, const char *, const char *);
98 static void berkeley_header(void);
99 static void berkeley_totals(void);
100 static int handle_core(char const *, Elf *elf, GElf_Ehdr *);
101 static void handle_core_note(Elf *, GElf_Ehdr *, GElf_Phdr *, char **);
102 static int handle_elf(int, char const *);
103 static void handle_phdr(Elf *, GElf_Ehdr *, GElf_Phdr *, uint32_t,
105 static void show_version(void);
106 static void sysv_header(const char *, Elf_Arhdr *);
107 static void sysv_footer(void);
108 static void sysv_calc(Elf *, GElf_Ehdr *, GElf_Shdr *);
109 static void usage(void);
110 static void tbl_new(int);
111 static void tbl_print(const char *, int);
112 static void tbl_print_num(uint64_t, enum radix_style, int);
113 static void tbl_append(void);
114 static void tbl_flush(void);
117 * size utility using elf(3) and gelf(3) API to list section sizes and
118 * total in elf files. Supports only elf files (core dumps in elf
119 * included) that can be opened by libelf, other formats are not supported.
122 main(int argc, char **argv)
132 if (elf_version(EV_CURRENT) == EV_NONE)
133 errx(EXIT_FAILURE, "ELF library initialization failed: %s",
136 while ((ch = getopt_long(argc, argv, "ABVdhotx", size_longopts,
143 style = STYLE_BERKELEY;
149 radix = RADIX_DECIMAL;
161 switch (size_option) {
163 if (*optarg == 's' || *optarg == 'S')
165 else if (*optarg == 'b' || *optarg == 'B')
166 style = STYLE_BERKELEY;
168 warnx("unrecognized format \"%s\".",
174 r = strtol(optarg, NULL, 10);
178 radix = RADIX_DECIMAL;
182 warnx("unsupported radix \"%s\".",
188 err(EXIT_FAILURE, "Error in option handling.");
202 defaultfn = strdup("a.out");
203 if (defaultfn == NULL)
204 err(EXIT_FAILURE, "strdup");
211 cap_rights_init(&rights, CAP_FSTAT, CAP_MMAP_R);
212 fa = fileargs_init(argc, argv, O_RDONLY, 0, &rights, FA_OPEN);
214 err(EXIT_FAILURE, "failed to initialize fileargs");
216 caph_cache_catpages();
217 if (caph_limit_stdio() < 0)
218 err(EXIT_FAILURE, "failed to limit stdio rights");
219 if (caph_enter_casper() < 0)
220 err(EXIT_FAILURE, "failed to enter capability mode");
222 for (; argc > 0; argc--, argv++) {
224 fd = fileargs_open(fa, fn);
226 warn("%s: Failed to open", fn);
229 rc = handle_elf(fd, fn);
231 warnx("%s: File format not recognized", fn);
233 if (style == STYLE_BERKELEY) {
244 xlatetom(Elf *elf, GElf_Ehdr *elfhdr, void *_src, void *_dst,
245 Elf_Type type, size_t size)
251 src.d_version = elfhdr->e_version;
254 dst.d_version = elfhdr->e_version;
256 return (gelf_xlatetom(elf, &dst, &src, elfhdr->e_ident[EI_DATA]) !=
260 #define NOTE_OFFSET_32(nhdr, namesz, offset) \
261 ((char *)nhdr + sizeof(Elf32_Nhdr) + \
262 ELF_ALIGN((int32_t)namesz, 4) + offset)
264 #define NOTE_OFFSET_64(nhdr, namesz, offset) \
265 ((char *)nhdr + sizeof(Elf32_Nhdr) + \
266 ELF_ALIGN((int32_t)namesz, 8) + offset)
268 #define PID32(nhdr, namesz, offset) \
269 (pid_t)*((int *)((uintptr_t)NOTE_OFFSET_32(nhdr, \
272 #define PID64(nhdr, namesz, offset) \
273 (pid_t)*((int *)((uintptr_t)NOTE_OFFSET_64(nhdr, \
276 #define NEXT_NOTE(elfhdr, descsz, namesz, offset) do { \
277 if (elfhdr->e_ident[EI_CLASS] == ELFCLASS32) { \
278 offset += ELF_ALIGN((int32_t)descsz, 4) + \
279 sizeof(Elf32_Nhdr) + \
280 ELF_ALIGN((int32_t)namesz, 4); \
282 offset += ELF_ALIGN((int32_t)descsz, 8) + \
283 sizeof(Elf32_Nhdr) + \
284 ELF_ALIGN((int32_t)namesz, 8); \
289 * Parse individual note entries inside a PT_NOTE segment.
292 handle_core_note(Elf *elf, GElf_Ehdr *elfhdr, GElf_Phdr *phdr,
295 size_t max_size, segment_end;
300 Elf32_Nhdr *nhdr, nhdr_l;
301 static int reg_pseudo = 0, reg2_pseudo = 0 /*, regxfp_pseudo = 0*/;
302 char buf[BUF_SIZE], *data, *name;
304 if (elf == NULL || elfhdr == NULL || phdr == NULL)
307 data = elf_rawfile(elf, &max_size);
308 offset = phdr->p_offset;
309 if (offset >= max_size || phdr->p_filesz > max_size - offset) {
310 warnx("invalid PHDR offset");
313 segment_end = phdr->p_offset + phdr->p_filesz;
315 while (data != NULL && offset + sizeof(Elf32_Nhdr) < segment_end) {
316 nhdr = (Elf32_Nhdr *)(uintptr_t)((char*)data + offset);
317 memset(&nhdr_l, 0, sizeof(Elf32_Nhdr));
318 if (xlatetom(elf, elfhdr, &nhdr->n_type, &nhdr_l.n_type,
319 ELF_T_WORD, sizeof(Elf32_Word)) != 0 ||
320 xlatetom(elf, elfhdr, &nhdr->n_descsz, &nhdr_l.n_descsz,
321 ELF_T_WORD, sizeof(Elf32_Word)) != 0 ||
322 xlatetom(elf, elfhdr, &nhdr->n_namesz, &nhdr_l.n_namesz,
323 ELF_T_WORD, sizeof(Elf32_Word)) != 0)
326 if (offset + sizeof(Elf32_Nhdr) +
327 ELF_ALIGN(nhdr_l.n_namesz, 4) +
328 ELF_ALIGN(nhdr_l.n_descsz, 4) >= segment_end) {
329 warnx("invalid note header");
333 name = (char *)((char *)nhdr + sizeof(Elf32_Nhdr));
334 switch (nhdr_l.n_type) {
337 if (elfhdr->e_ident[EI_OSABI] == ELFOSABI_FREEBSD &&
338 nhdr_l.n_namesz == 0x8 &&
339 !strcmp(name,"FreeBSD")) {
340 if (elfhdr->e_ident[EI_CLASS] == ELFCLASS32) {
341 raw_size = (uint64_t)*((uint32_t *)
344 nhdr_l.n_namesz, 4) + 8));
345 ver = (uintptr_t)NOTE_OFFSET_32(nhdr,
347 if (*((int *)ver) == 1)
349 nhdr_l.n_namesz, 24);
351 raw_size = *((uint64_t *)(uintptr_t)
352 (name + ELF_ALIGN((int32_t)
353 nhdr_l.n_namesz, 8) + 16));
354 ver = (uintptr_t)NOTE_OFFSET_64(nhdr,
356 if (*((int *)ver) == 1)
358 nhdr_l.n_namesz, 40);
360 (void)xlatetom(elf, elfhdr, &raw_size,
361 &raw_size, ELF_T_WORD, sizeof(uint64_t));
362 (void)xlatetom(elf, elfhdr, &pid, &pid,
363 ELF_T_WORD, sizeof(pid_t));
366 if (raw_size != 0 && style == STYLE_SYSV) {
367 (void) snprintf(buf, BUF_SIZE, "%s/%d",
371 tbl_print_num(raw_size, radix, 1);
372 tbl_print_num(0, radix, 2);
375 tbl_print(".reg", 0);
376 tbl_print_num(raw_size, radix, 1);
377 tbl_print_num(0, radix, 2);
379 text_size_total += raw_size;
381 text_size_total += raw_size;
385 case NT_FPREGSET: /* same as NT_PRFPREG */
386 if (style == STYLE_SYSV) {
387 (void) snprintf(buf, BUF_SIZE,
388 "%s/%d", ".reg2", pid);
391 tbl_print_num(nhdr_l.n_descsz, radix, 1);
392 tbl_print_num(0, radix, 2);
395 tbl_print(".reg2", 0);
396 tbl_print_num(nhdr_l.n_descsz, radix,
398 tbl_print_num(0, radix, 2);
400 text_size_total += nhdr_l.n_descsz;
402 text_size_total += nhdr_l.n_descsz;
407 if (style == STYLE_SYSV) {
409 tbl_print(".auxv", 0);
410 tbl_print_num(nhdr_l.n_descsz, radix, 1);
411 tbl_print_num(0, radix, 2);
412 text_size_total += nhdr_l.n_descsz;
416 if (style == STYLE_SYSV) {
417 (void) snprintf(buf, BUF_SIZE, "%s/%d",
421 tbl_print_num(nhdr_l.n_descsz, radix, 1);
422 tbl_print_num(0, radix, 2);
423 if (!regxfp_pseudo) {
425 tbl_print(".reg-xfp", 0);
426 tbl_print_num(nhdr_l.n_descsz, radix,
428 tbl_print_num(0, radix, 2);
430 text_size_total += nhdr_l.n_descsz;
432 text_size_total += nhdr_l.n_descsz;
439 if (nhdr_l.n_descsz == 0x78 &&
440 !strcmp(name,"FreeBSD")) {
441 *cmd_line = strdup(NOTE_OFFSET_64(nhdr,
442 nhdr_l.n_namesz, 33));
444 } else if (nhdr_l.n_descsz == 0x6c &&
445 !strcmp(name,"FreeBSD")) {
446 *cmd_line = strdup(NOTE_OFFSET_32(nhdr,
447 nhdr_l.n_namesz, 25));
449 /* Strip any trailing spaces */
450 if (*cmd_line != NULL) {
453 s = *cmd_line + strlen(*cmd_line);
454 while (s > *cmd_line) {
455 if (*(s-1) != 0x20) break;
469 NEXT_NOTE(elfhdr, nhdr_l.n_descsz, nhdr_l.n_namesz, offset);
474 * Handles program headers except for PT_NOTE, when sysv output style is
475 * chosen, prints out the segment name and length. For berkely output
476 * style only PT_LOAD segments are handled, and text,
477 * data, bss size is calculated for them.
480 handle_phdr(Elf *elf, GElf_Ehdr *elfhdr, GElf_Phdr *phdr,
481 uint32_t idx, const char *name)
487 if (elf == NULL || elfhdr == NULL || phdr == NULL)
490 split = (phdr->p_memsz > 0) && (phdr->p_filesz > 0) &&
491 (phdr->p_memsz > phdr->p_filesz);
493 if (style == STYLE_SYSV) {
494 (void) snprintf(buf, BUF_SIZE,
495 "%s%d%s", name, idx, (split ? "a" : ""));
498 tbl_print_num(phdr->p_filesz, radix, 1);
499 tbl_print_num(phdr->p_vaddr, radix, 2);
500 text_size_total += phdr->p_filesz;
502 size = phdr->p_memsz - phdr->p_filesz;
503 addr = phdr->p_vaddr + phdr->p_filesz;
504 (void) snprintf(buf, BUF_SIZE, "%s%d%s", name,
506 text_size_total += phdr->p_memsz - phdr->p_filesz;
509 tbl_print_num(size, radix, 1);
510 tbl_print_num(addr, radix, 2);
513 if (phdr->p_type != PT_LOAD)
515 if ((phdr->p_flags & PF_W) && !(phdr->p_flags & PF_X)) {
516 data_size += phdr->p_filesz;
518 data_size += phdr->p_memsz - phdr->p_filesz;
520 text_size += phdr->p_filesz;
522 text_size += phdr->p_memsz - phdr->p_filesz;
528 * Given a core dump file, this function maps program headers to segments.
531 handle_core(char const *name, Elf *elf, GElf_Ehdr *elfhdr)
536 const char *seg_name;
538 if (name == NULL || elf == NULL || elfhdr == NULL)
539 return (RETURN_DATAERR);
540 if (elfhdr->e_shnum != 0 || elfhdr->e_type != ET_CORE)
541 return (RETURN_DATAERR);
543 seg_name = core_cmdline = NULL;
544 if (style == STYLE_SYSV)
545 sysv_header(name, NULL);
549 for (i = 0; i < elfhdr->e_phnum; i++) {
550 if (gelf_getphdr(elf, i, &phdr) != NULL) {
551 if (phdr.p_type == PT_NOTE) {
552 handle_phdr(elf, elfhdr, &phdr, i, "note");
553 handle_core_note(elf, elfhdr, &phdr,
556 switch(phdr.p_type) {
564 seg_name = "dynamic";
575 case PT_GNU_EH_FRAME:
576 seg_name = "eh_frame_hdr";
582 seg_name = "segment";
584 handle_phdr(elf, elfhdr, &phdr, i, seg_name);
589 if (style == STYLE_BERKELEY) {
590 if (core_cmdline != NULL) {
591 berkeley_footer(core_cmdline, name,
592 "core file invoked as");
594 berkeley_footer(core_cmdline, name, "core file");
598 if (core_cmdline != NULL) {
599 (void) printf(" (core file invoked as %s)\n\n",
602 (void) printf(" (core file)\n\n");
610 * Given an elf object,ar(1) filename, and based on the output style
611 * and radix format the various sections and their length will be printed
612 * or the size of the text, data, bss sections will be printed out.
615 handle_elf(int fd, const char *name)
625 elf_cmd = ELF_C_READ;
626 elf1 = elf_begin(fd, elf_cmd, NULL);
627 while ((elf = elf_begin(fd, elf_cmd, elf1)) != NULL) {
628 arhdr = elf_getarhdr(elf);
629 if (elf_kind(elf) == ELF_K_NONE && arhdr == NULL) {
631 (void) elf_end(elf1);
633 return (RETURN_DATAERR);
635 if (elf_kind(elf) != ELF_K_ELF ||
636 (gelf_getehdr(elf, &elfhdr) == NULL)) {
637 elf_cmd = elf_next(elf);
639 warnx("%s: File format not recognized",
640 arhdr != NULL ? arhdr->ar_name : name);
643 /* Core dumps are handled separately */
644 if (elfhdr.e_shnum == 0 && elfhdr.e_type == ET_CORE) {
645 exit_code = handle_core(name, elf, &elfhdr);
647 (void) elf_end(elf1);
652 if (style == STYLE_BERKELEY) {
654 while ((scn = elf_nextscn(elf, scn)) != NULL) {
655 if (gelf_getshdr(scn, &shdr) != NULL)
656 berkeley_calc(&shdr);
659 sysv_header(name, arhdr);
661 while ((scn = elf_nextscn(elf, scn)) != NULL) {
662 if (gelf_getshdr(scn, &shdr) != NULL)
663 sysv_calc(elf, &elfhdr, &shdr);
666 if (style == STYLE_BERKELEY) {
668 berkeley_footer(name, arhdr->ar_name,
671 berkeley_footer(name, NULL, "ex");
677 elf_cmd = elf_next(elf);
680 (void) elf_end(elf1);
686 * Sysv formatting helper functions.
689 sysv_header(const char *name, Elf_Arhdr *arhdr)
694 (void) printf("%s (ex %s):\n", arhdr->ar_name, name);
696 (void) printf("%s :\n", name);
699 tbl_print("section", 0);
700 tbl_print("size", 1);
701 tbl_print("addr", 2);
705 sysv_calc(Elf *elf, GElf_Ehdr *elfhdr, GElf_Shdr *shdr)
709 section_name = elf_strptr(elf, elfhdr->e_shstrndx,
710 (size_t) shdr->sh_name);
711 if ((shdr->sh_type == SHT_SYMTAB ||
712 shdr->sh_type == SHT_STRTAB || shdr->sh_type == SHT_RELA ||
713 shdr->sh_type == SHT_REL) && shdr->sh_addr == 0)
716 tbl_print(section_name, 0);
717 tbl_print_num(shdr->sh_size, radix, 1);
718 tbl_print_num(shdr->sh_addr, radix, 2);
719 text_size_total += shdr->sh_size;
726 tbl_print("Total", 0);
727 tbl_print_num(text_size_total, radix, 1);
733 * berkeley style output formatting helper functions.
736 berkeley_header(void)
740 text_size = data_size = bss_size = 0;
744 tbl_print("text", 0);
745 tbl_print("data", 1);
747 if (radix == RADIX_OCTAL)
752 tbl_print("filename", 5);
758 berkeley_calc(GElf_Shdr *shdr)
761 if (!(shdr->sh_flags & SHF_ALLOC))
763 if ((shdr->sh_flags & SHF_ALLOC) &&
764 ((shdr->sh_flags & SHF_EXECINSTR) ||
765 !(shdr->sh_flags & SHF_WRITE)))
766 text_size += shdr->sh_size;
767 else if ((shdr->sh_flags & SHF_ALLOC) &&
768 (shdr->sh_flags & SHF_WRITE) &&
769 (shdr->sh_type != SHT_NOBITS))
770 data_size += shdr->sh_size;
772 bss_size += shdr->sh_size;
777 berkeley_totals(void)
779 uint64_t grand_total;
781 grand_total = text_size_total + data_size_total + bss_size_total;
783 tbl_print_num(text_size_total, radix, 0);
784 tbl_print_num(data_size_total, radix, 1);
785 tbl_print_num(bss_size_total, radix, 2);
786 if (radix == RADIX_OCTAL)
787 tbl_print_num(grand_total, RADIX_OCTAL, 3);
789 tbl_print_num(grand_total, RADIX_DECIMAL, 3);
790 tbl_print_num(grand_total, RADIX_HEX, 4);
794 berkeley_footer(const char *name, const char *ar_name, const char *msg)
798 total_size = text_size + data_size + bss_size;
800 text_size_total += text_size;
801 bss_size_total += bss_size;
802 data_size_total += data_size;
806 tbl_print_num(text_size, radix, 0);
807 tbl_print_num(data_size, radix, 1);
808 tbl_print_num(bss_size, radix, 2);
809 if (radix == RADIX_OCTAL)
810 tbl_print_num(total_size, RADIX_OCTAL, 3);
812 tbl_print_num(total_size, RADIX_DECIMAL, 3);
813 tbl_print_num(total_size, RADIX_HEX, 4);
814 if (ar_name != NULL && name != NULL)
815 (void) snprintf(buf, BUF_SIZE, "%s (%s %s)", ar_name, msg,
817 else if (ar_name != NULL && name == NULL)
818 (void) snprintf(buf, BUF_SIZE, "%s (%s)", ar_name, msg);
820 (void) snprintf(buf, BUF_SIZE, "%s", name);
831 if ((tb = calloc(1, sizeof(*tb))) == NULL)
832 err(EXIT_FAILURE, "calloc");
833 if ((tb->tbl = calloc(col, sizeof(*tb->tbl))) == NULL)
834 err(EXIT_FAILURE, "calloc");
835 if ((tb->width = calloc(col, sizeof(*tb->width))) == NULL)
836 err(EXIT_FAILURE, "calloc");
842 tbl_print(const char *s, int col)
846 assert(tb != NULL && tb->col > 0 && tb->row > 0 && col < tb->col);
847 assert(s != NULL && tb->tbl[col][tb->row - 1] == NULL);
848 if ((tb->tbl[col][tb->row - 1] = strdup(s)) == NULL)
849 err(EXIT_FAILURE, "strdup");
851 if (len > tb->width[col])
852 tb->width[col] = len;
856 tbl_print_num(uint64_t num, enum radix_style rad, int col)
860 (void) snprintf(buf, BUF_SIZE, (rad == RADIX_DECIMAL ? "%ju" :
861 ((rad == RADIX_OCTAL) ? "0%jo" : "0x%jx")), (uintmax_t) num);
870 assert(tb != NULL && tb->col > 0);
872 for (i = 0; i < tb->col; i++) {
873 tb->tbl[i] = realloc(tb->tbl[i], sizeof(*tb->tbl[i]) * tb->row);
874 if (tb->tbl[i] == NULL)
875 err(EXIT_FAILURE, "realloc");
876 tb->tbl[i][tb->row - 1] = NULL;
890 for (i = 0; i < tb->row; i++) {
891 if (style == STYLE_BERKELEY)
893 for (j = 0; j < tb->col; j++) {
894 str = (tb->tbl[j][i] != NULL ? tb->tbl[j][i] : "");
895 if (style == STYLE_SYSV && j == 0)
896 printf("%-*s", tb->width[j], str);
897 else if (style == STYLE_BERKELEY && j == tb->col - 1)
900 printf("%*s", tb->width[j], str);
908 for (i = 0; i < tb->col; i++) {
909 for (j = 0; j < tb->row; j++) {
921 #define USAGE_MESSAGE "\
922 Usage: %s [options] file ...\n\
923 Display sizes of ELF sections.\n\n\
925 --format=format Display output in specified format. Supported\n\
926 values are `berkeley' and `sysv'.\n\
927 --help Display this help message and exit.\n\
928 --radix=radix Display numeric values in the specified radix.\n\
929 Supported values are: 8, 10 and 16.\n\
930 --totals Show cumulative totals of section sizes.\n\
931 --version Display a version identifier and exit.\n\
932 -A Equivalent to `--format=sysv'.\n\
933 -B Equivalent to `--format=berkeley'.\n\
934 -V Equivalent to `--version'.\n\
935 -d Equivalent to `--radix=10'.\n\
936 -h Same as option --help.\n\
937 -o Equivalent to `--radix=8'.\n\
938 -t Equivalent to option --totals.\n\
939 -x Equivalent to `--radix=16'.\n"
944 (void) fprintf(stderr, USAGE_MESSAGE, ELFTC_GETPROGNAME());
951 (void) printf("%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version());