size.c revision 275192
1/*-
2 * Copyright (c) 2007 S.Sam Arun Raj
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
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.
13 *
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
24 * SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28#include <assert.h>
29#include <err.h>
30#include <fcntl.h>
31#include <gelf.h>
32#include <getopt.h>
33#include <libelftc.h>
34#include <stdint.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <unistd.h>
39
40#include "_elftc.h"
41
42ELFTC_VCSID("$Id: size.c 2350 2011-12-19 10:20:06Z jkoshy $");
43
44#define	BUF_SIZE			1024
45#define	ELF_ALIGN(val,x) (((val)+(x)-1) & ~((x)-1))
46#define	SIZE_VERSION_STRING		"size 1.0"
47
48enum return_code {
49	RETURN_OK,
50	RETURN_NOINPUT,
51	RETURN_DATAERR,
52	RETURN_USAGE
53};
54
55enum output_style {
56	STYLE_BERKELEY,
57	STYLE_SYSV
58};
59
60enum radix_style {
61	RADIX_OCTAL,
62	RADIX_DECIMAL,
63	RADIX_HEX
64};
65
66static uint64_t bss_size, data_size, text_size, total_size;
67static uint64_t bss_size_total, data_size_total, text_size_total;
68static int show_totals;
69static int size_option;
70static enum radix_style radix = RADIX_DECIMAL;
71static enum output_style style = STYLE_BERKELEY;
72static const char *default_args[2] = { "a.out", NULL };
73
74static struct {
75	int row;
76	int col;
77	int *width;
78	char ***tbl;
79} *tb;
80
81enum {
82	OPT_FORMAT,
83	OPT_RADIX
84};
85
86static struct option size_longopts[] = {
87	{ "format",	required_argument, &size_option, OPT_FORMAT },
88	{ "help",	no_argument,	NULL,	'h' },
89	{ "radix",	required_argument, &size_option, OPT_RADIX },
90	{ "totals",	no_argument,	NULL,	't' },
91	{ "version",	no_argument,	NULL,	'V' },
92	{ NULL, 0, NULL, 0 }
93};
94
95static void	berkeley_calc(GElf_Shdr *);
96static void	berkeley_footer(const char *, const char *, const char *);
97static void	berkeley_header(void);
98static void	berkeley_totals(void);
99static int	handle_core(char const *, Elf *elf, GElf_Ehdr *);
100static void	handle_core_note(Elf *, GElf_Ehdr *, GElf_Phdr *, char **);
101static int	handle_elf(char const *);
102static void	handle_phdr(Elf *, GElf_Ehdr *, GElf_Phdr *, uint32_t,
103		    const char *);
104static void	show_version(void);
105static void	sysv_header(const char *, Elf_Arhdr *);
106static void	sysv_footer(void);
107static void	sysv_calc(Elf *, GElf_Ehdr *, GElf_Shdr *);
108static void	usage(void);
109static void	tbl_new(int);
110static void	tbl_print(const char *, int);
111static void	tbl_print_num(uint64_t, enum radix_style, int);
112static void	tbl_append(void);
113static void	tbl_flush(void);
114
115/*
116 * size utility using elf(3) and gelf(3) API to list section sizes and
117 * total in elf files. Supports only elf files (core dumps in elf
118 * included) that can be opened by libelf, other formats are not supported.
119 */
120int
121main(int argc, char **argv)
122{
123	int ch, r, rc;
124	const char **files, *fn;
125
126	rc = RETURN_OK;
127
128	if (elf_version(EV_CURRENT) == EV_NONE)
129		errx(EXIT_FAILURE, "ELF library initialization failed: %s",
130		    elf_errmsg(-1));
131
132	while ((ch = getopt_long(argc, argv, "ABVdhotx", size_longopts,
133	    NULL)) != -1)
134		switch((char)ch) {
135		case 'A':
136			style = STYLE_SYSV;
137			break;
138		case 'B':
139			style = STYLE_BERKELEY;
140			break;
141		case 'V':
142			show_version();
143			break;
144		case 'd':
145			radix = RADIX_DECIMAL;
146			break;
147		case 'o':
148			radix = RADIX_OCTAL;
149			break;
150		case 't':
151			show_totals = 1;
152			break;
153		case 'x':
154			radix = RADIX_HEX;
155			break;
156		case 0:
157			switch (size_option) {
158			case OPT_FORMAT:
159				if (*optarg == 's' || *optarg == 'S')
160					style = STYLE_SYSV;
161				else if (*optarg == 'b' || *optarg == 'B')
162					style = STYLE_BERKELEY;
163				else {
164					warnx("unrecognized format \"%s\".",
165					      optarg);
166					usage();
167				}
168				break;
169			case OPT_RADIX:
170				r = strtol(optarg, NULL, 10);
171				if (r == 8)
172					radix = RADIX_OCTAL;
173				else if (r == 10)
174					radix = RADIX_DECIMAL;
175				else if (r == 16)
176					radix = RADIX_HEX;
177				else {
178					warnx("unsupported radix \"%s\".",
179					      optarg);
180					usage();
181				}
182				break;
183			default:
184				err(EXIT_FAILURE, "Error in option handling.");
185				/*NOTREACHED*/
186			}
187			break;
188		case 'h':
189		case '?':
190		default:
191			usage();
192			/* NOTREACHED */
193		}
194	argc -= optind;
195	argv += optind;
196
197	files = (argc == 0) ? default_args : (void *) argv;
198
199	while ((fn = *files) != NULL) {
200		rc = handle_elf(fn);
201		if (rc != RETURN_OK)
202			warnx(rc == RETURN_NOINPUT ?
203			      "'%s': No such file" :
204			      "%s: File format not recognized", fn);
205		files++;
206	}
207	if (style == STYLE_BERKELEY) {
208		if (show_totals)
209			berkeley_totals();
210		tbl_flush();
211	}
212        return (rc);
213}
214
215static Elf_Data *
216xlatetom(Elf *elf, GElf_Ehdr *elfhdr, void *_src, void *_dst,
217    Elf_Type type, size_t size)
218{
219	Elf_Data src, dst;
220
221	src.d_buf = _src;
222	src.d_type = type;
223	src.d_version = elfhdr->e_version;
224	src.d_size = size;
225	dst.d_buf = _dst;
226	dst.d_version = elfhdr->e_version;
227	dst.d_size = size;
228	return (gelf_xlatetom(elf, &dst, &src, elfhdr->e_ident[EI_DATA]));
229}
230
231#define NOTE_OFFSET_32(nhdr, namesz, offset) 			\
232	((char *)nhdr + sizeof(Elf32_Nhdr) +			\
233	    ELF_ALIGN((int32_t)namesz, 4) + offset)
234
235#define NOTE_OFFSET_64(nhdr, namesz, offset) 			\
236	((char *)nhdr + sizeof(Elf32_Nhdr) +			\
237	    ELF_ALIGN((int32_t)namesz, 8) + offset)
238
239#define PID32(nhdr, namesz, offset) 				\
240	(pid_t)*((int *)((uintptr_t)NOTE_OFFSET_32(nhdr,	\
241	    namesz, offset)));
242
243#define PID64(nhdr, namesz, offset) 				\
244	(pid_t)*((int *)((uintptr_t)NOTE_OFFSET_64(nhdr,	\
245	    namesz, offset)));
246
247#define NEXT_NOTE(elfhdr, descsz, namesz, offset) do {		\
248	if (elfhdr->e_ident[EI_CLASS] == ELFCLASS32) { 		\
249		offset += ELF_ALIGN((int32_t)descsz, 4) +	\
250		    sizeof(Elf32_Nhdr) + 			\
251			ELF_ALIGN((int32_t)namesz, 4); 		\
252	} else {						\
253		offset += ELF_ALIGN((int32_t)descsz, 8) + 	\
254		    sizeof(Elf32_Nhdr) + 			\
255		        ELF_ALIGN((int32_t)namesz, 8); 		\
256	}							\
257} while (0)
258
259/*
260 * Parse individual note entries inside a PT_NOTE segment.
261 */
262static void
263handle_core_note(Elf *elf, GElf_Ehdr *elfhdr, GElf_Phdr *phdr,
264    char **cmd_line)
265{
266	size_t max_size;
267	uint64_t raw_size;
268	GElf_Off offset;
269	static pid_t pid;
270	uintptr_t ver;
271	Elf32_Nhdr *nhdr, nhdr_l;
272	static int reg_pseudo = 0, reg2_pseudo = 0, regxfp_pseudo = 0;
273	char buf[BUF_SIZE], *data, *name;
274
275 	if (elf == NULL || elfhdr == NULL || phdr == NULL)
276		return;
277
278	data = elf_rawfile(elf, &max_size);
279	offset = phdr->p_offset;
280	while (data != NULL && offset < phdr->p_offset + phdr->p_filesz) {
281		nhdr = (Elf32_Nhdr *)(uintptr_t)((char*)data + offset);
282		memset(&nhdr_l, 0, sizeof(Elf32_Nhdr));
283		if (!xlatetom(elf, elfhdr, &nhdr->n_type, &nhdr_l.n_type,
284			ELF_T_WORD, sizeof(Elf32_Word)) ||
285		    !xlatetom(elf, elfhdr, &nhdr->n_descsz, &nhdr_l.n_descsz,
286			ELF_T_WORD, sizeof(Elf32_Word)) ||
287		    !xlatetom(elf, elfhdr, &nhdr->n_namesz, &nhdr_l.n_namesz,
288			ELF_T_WORD, sizeof(Elf32_Word)))
289			break;
290
291		name = (char *)((char *)nhdr + sizeof(Elf32_Nhdr));
292		switch (nhdr_l.n_type) {
293		case NT_PRSTATUS: {
294			raw_size = 0;
295			if (elfhdr->e_ident[EI_OSABI] == ELFOSABI_FREEBSD &&
296			    nhdr_l.n_namesz == 0x8 &&
297			    !strcmp(name,"FreeBSD")) {
298				if (elfhdr->e_ident[EI_CLASS] == ELFCLASS32) {
299					raw_size = (uint64_t)*((uint32_t *)
300					    (uintptr_t)(name +
301						ELF_ALIGN((int32_t)
302						nhdr_l.n_namesz, 4) + 8));
303					ver = (uintptr_t)NOTE_OFFSET_32(nhdr,
304					    nhdr_l.n_namesz,0);
305					if (*((int *)ver) == 1)
306						pid = PID32(nhdr,
307						    nhdr_l.n_namesz, 24);
308				} else {
309					raw_size = *((uint64_t *)(uintptr_t)
310					    (name + ELF_ALIGN((int32_t)
311						nhdr_l.n_namesz, 8) + 16));
312					ver = (uintptr_t)NOTE_OFFSET_64(nhdr,
313					    nhdr_l.n_namesz,0);
314					if (*((int *)ver) == 1)
315						pid = PID64(nhdr,
316						    nhdr_l.n_namesz, 40);
317				}
318				xlatetom(elf, elfhdr, &raw_size, &raw_size,
319				    ELF_T_WORD, sizeof(uint64_t));
320				xlatetom(elf, elfhdr, &pid, &pid, ELF_T_WORD,
321				    sizeof(pid_t));
322			}
323
324			if (raw_size != 0 && style == STYLE_SYSV) {
325				(void) snprintf(buf, BUF_SIZE, "%s/%d",
326				    ".reg", pid);
327				tbl_append();
328				tbl_print(buf, 0);
329				tbl_print_num(raw_size, radix, 1);
330				tbl_print_num(0, radix, 2);
331				if (!reg_pseudo) {
332					tbl_append();
333					tbl_print(".reg", 0);
334					tbl_print_num(raw_size, radix, 1);
335					tbl_print_num(0, radix, 2);
336					reg_pseudo = 1;
337					text_size_total += raw_size;
338				}
339				text_size_total += raw_size;
340			}
341		}
342		break;
343		case NT_FPREGSET:	/* same as NT_PRFPREG */
344			if (style == STYLE_SYSV) {
345				(void) snprintf(buf, BUF_SIZE,
346				    "%s/%d", ".reg2", pid);
347				tbl_append();
348				tbl_print(buf, 0);
349				tbl_print_num(nhdr_l.n_descsz, radix, 1);
350				tbl_print_num(0, radix, 2);
351				if (!reg2_pseudo) {
352					tbl_append();
353					tbl_print(".reg2", 0);
354					tbl_print_num(nhdr_l.n_descsz, radix,
355					    1);
356					tbl_print_num(0, radix, 2);
357					reg2_pseudo = 1;
358					text_size_total += nhdr_l.n_descsz;
359				}
360				text_size_total += nhdr_l.n_descsz;
361			}
362			break;
363		case NT_AUXV:
364			if (style == STYLE_SYSV) {
365				tbl_append();
366				tbl_print(".auxv", 0);
367				tbl_print_num(nhdr_l.n_descsz, radix, 1);
368				tbl_print_num(0, radix, 2);
369				text_size_total += nhdr_l.n_descsz;
370			}
371			break;
372		case NT_PRXFPREG:
373			if (style == STYLE_SYSV) {
374				(void) snprintf(buf, BUF_SIZE, "%s/%d",
375				    ".reg-xfp", pid);
376				tbl_append();
377				tbl_print(buf, 0);
378				tbl_print_num(nhdr_l.n_descsz, radix, 1);
379				tbl_print_num(0, radix, 2);
380				if (!regxfp_pseudo) {
381					tbl_append();
382					tbl_print(".reg-xfp", 0);
383					tbl_print_num(nhdr_l.n_descsz, radix,
384					    1);
385					tbl_print_num(0, radix, 2);
386					regxfp_pseudo = 1;
387					text_size_total += nhdr_l.n_descsz;
388				}
389				text_size_total += nhdr_l.n_descsz;
390			}
391			break;
392		case NT_PSINFO:
393		case NT_PRPSINFO: {
394			/* FreeBSD 64-bit */
395			if (nhdr_l.n_descsz == 0x78 &&
396				!strcmp(name,"FreeBSD")) {
397				*cmd_line = strdup(NOTE_OFFSET_64(nhdr,
398				    nhdr_l.n_namesz, 33));
399			/* FreeBSD 32-bit */
400			} else if (nhdr_l.n_descsz == 0x6c &&
401				!strcmp(name,"FreeBSD")) {
402				*cmd_line = strdup(NOTE_OFFSET_32(nhdr,
403				    nhdr_l.n_namesz, 25));
404			}
405			/* Strip any trailing spaces */
406			if (*cmd_line != NULL) {
407				char *s;
408
409				s = *cmd_line + strlen(*cmd_line);
410				while (s > *cmd_line) {
411					if (*(s-1) != 0x20) break;
412					s--;
413				}
414				*s = 0;
415			}
416			break;
417		}
418		case NT_PSTATUS:
419		case NT_LWPSTATUS:
420		default:
421			break;
422		}
423		NEXT_NOTE(elfhdr, nhdr_l.n_descsz, nhdr_l.n_namesz, offset);
424	}
425}
426
427/*
428 * Handles program headers except for PT_NOTE, when sysv output stlye is
429 * choosen, prints out the segment name and length. For berkely output
430 * style only PT_LOAD segments are handled, and text,
431 * data, bss size is calculated for them.
432 */
433static void
434handle_phdr(Elf *elf, GElf_Ehdr *elfhdr, GElf_Phdr *phdr,
435    uint32_t idx, const char *name)
436{
437	uint64_t addr, size;
438	int split;
439	char buf[BUF_SIZE];
440
441	if (elf == NULL || elfhdr == NULL || phdr == NULL)
442		return;
443
444	size = addr = 0;
445	split = (phdr->p_memsz > 0) && 	(phdr->p_filesz > 0) &&
446	    (phdr->p_memsz > phdr->p_filesz);
447
448	if (style == STYLE_SYSV) {
449		(void) snprintf(buf, BUF_SIZE,
450		    "%s%d%s", name, idx, (split ? "a" : ""));
451		tbl_append();
452		tbl_print(buf, 0);
453		tbl_print_num(phdr->p_filesz, radix, 1);
454		tbl_print_num(phdr->p_vaddr, radix, 2);
455		text_size_total += phdr->p_filesz;
456		if (split) {
457			size = phdr->p_memsz - phdr->p_filesz;
458			addr = phdr->p_vaddr + phdr->p_filesz;
459			(void) snprintf(buf, BUF_SIZE, "%s%d%s", name,
460			    idx, "b");
461			text_size_total += phdr->p_memsz - phdr->p_filesz;
462			tbl_append();
463			tbl_print(buf, 0);
464			tbl_print_num(size, radix, 1);
465			tbl_print_num(addr, radix, 2);
466		}
467	} else {
468		if (phdr->p_type != PT_LOAD)
469			return;
470		if ((phdr->p_flags & PF_W) && !(phdr->p_flags & PF_X)) {
471			data_size += phdr->p_filesz;
472			if (split)
473				data_size += phdr->p_memsz - phdr->p_filesz;
474		} else {
475			text_size += phdr->p_filesz;
476			if (split)
477				text_size += phdr->p_memsz - phdr->p_filesz;
478		}
479	}
480}
481
482/*
483 * Given a core dump file, this function maps program headers to segments.
484 */
485static int
486handle_core(char const *name, Elf *elf, GElf_Ehdr *elfhdr)
487{
488	GElf_Phdr phdr;
489	uint32_t i;
490	char *core_cmdline;
491	const char *seg_name;
492
493	if (name == NULL || elf == NULL || elfhdr == NULL)
494		return (RETURN_DATAERR);
495	if  (elfhdr->e_shnum != 0 || elfhdr->e_type != ET_CORE)
496		return (RETURN_DATAERR);
497
498	seg_name = core_cmdline = NULL;
499	if (style == STYLE_SYSV)
500		sysv_header(name, NULL);
501	else
502		berkeley_header();
503
504	for (i = 0; i < elfhdr->e_phnum; i++) {
505		if (gelf_getphdr(elf, i, &phdr) != NULL) {
506			if (phdr.p_type == PT_NOTE) {
507				handle_phdr(elf, elfhdr, &phdr, i, "note");
508				handle_core_note(elf, elfhdr, &phdr,
509				    &core_cmdline);
510			} else {
511				switch(phdr.p_type) {
512				case PT_NULL:
513					seg_name = "null";
514					break;
515				case PT_LOAD:
516					seg_name = "load";
517					break;
518				case PT_DYNAMIC:
519					seg_name = "dynamic";
520					break;
521				case PT_INTERP:
522					seg_name = "interp";
523					break;
524				case PT_SHLIB:
525					seg_name = "shlib";
526					break;
527				case PT_PHDR:
528					seg_name = "phdr";
529					break;
530				case PT_GNU_EH_FRAME:
531					seg_name = "eh_frame_hdr";
532					break;
533				case PT_GNU_STACK:
534					seg_name = "stack";
535					break;
536				default:
537					seg_name = "segment";
538				}
539				handle_phdr(elf, elfhdr, &phdr, i, seg_name);
540			}
541		}
542	}
543
544	if (style == STYLE_BERKELEY) {
545		if (core_cmdline != NULL) {
546			berkeley_footer(core_cmdline, name,
547			    "core file invoked as");
548		} else {
549			berkeley_footer(core_cmdline, name, "core file");
550		}
551	} else {
552		sysv_footer();
553		if (core_cmdline != NULL) {
554			(void) printf(" (core file invoked as %s)\n\n",
555			    core_cmdline);
556		} else {
557			(void) printf(" (core file)\n\n");
558		}
559	}
560	free(core_cmdline);
561	return (RETURN_OK);
562}
563
564/*
565 * Given an elf object,ar(1) filename, and based on the output style
566 * and radix format the various sections and their length will be printed
567 * or the size of the text, data, bss sections will be printed out.
568 */
569static int
570handle_elf(char const *name)
571{
572	GElf_Ehdr elfhdr;
573	GElf_Shdr shdr;
574	Elf *elf, *elf1;
575	Elf_Arhdr *arhdr;
576	Elf_Scn *scn;
577	Elf_Cmd elf_cmd;
578	int exit_code, fd;
579
580	if (name == NULL)
581		return (RETURN_NOINPUT);
582
583	if ((fd = open(name, O_RDONLY, 0)) < 0)
584		return (RETURN_NOINPUT);
585
586	elf_cmd = ELF_C_READ;
587	elf1 = elf_begin(fd, elf_cmd, NULL);
588	while ((elf = elf_begin(fd, elf_cmd, elf1)) != NULL) {
589		arhdr = elf_getarhdr(elf);
590		if (elf_kind(elf) == ELF_K_NONE && arhdr == NULL) {
591			(void) elf_end(elf);
592			(void) elf_end(elf1);
593			(void) close(fd);
594			return (RETURN_DATAERR);
595		}
596		if (elf_kind(elf) != ELF_K_ELF ||
597		    (gelf_getehdr(elf, &elfhdr) == NULL)) {
598			elf_cmd = elf_next(elf);
599			(void) elf_end(elf);
600			warnx("%s: File format not recognized",
601			    arhdr->ar_name);
602			continue;
603		}
604		/* Core dumps are handled seperately */
605		if (elfhdr.e_shnum == 0 && elfhdr.e_type == ET_CORE) {
606			exit_code = handle_core(name, elf, &elfhdr);
607			(void) elf_end(elf);
608			(void) elf_end(elf1);
609			(void) close(fd);
610			return (exit_code);
611		} else {
612			scn = NULL;
613			if (style == STYLE_BERKELEY) {
614				berkeley_header();
615				while ((scn = elf_nextscn(elf, scn)) != NULL) {
616					if (gelf_getshdr(scn, &shdr) != NULL)
617						berkeley_calc(&shdr);
618				}
619			} else {
620				sysv_header(name, arhdr);
621				scn = NULL;
622				while ((scn = elf_nextscn(elf, scn)) != NULL) {
623					if (gelf_getshdr(scn, &shdr) !=	NULL)
624						sysv_calc(elf, &elfhdr, &shdr);
625				}
626			}
627			if (style == STYLE_BERKELEY) {
628				if (arhdr != NULL) {
629					berkeley_footer(name, arhdr->ar_name,
630					    "ex");
631				} else {
632					berkeley_footer(name, NULL, "ex");
633				}
634			} else {
635				sysv_footer();
636			}
637		}
638		elf_cmd = elf_next(elf);
639		(void) elf_end(elf);
640	}
641	(void) elf_end(elf1);
642	(void) close(fd);
643	return (RETURN_OK);
644}
645
646/*
647 * Sysv formatting helper functions.
648 */
649static void
650sysv_header(const char *name, Elf_Arhdr *arhdr)
651{
652
653	text_size_total = 0;
654	if (arhdr != NULL)
655		(void) printf("%s   (ex %s):\n", arhdr->ar_name, name);
656	else
657		(void) printf("%s  :\n", name);
658	tbl_new(3);
659	tbl_append();
660	tbl_print("section", 0);
661	tbl_print("size", 1);
662	tbl_print("addr", 2);
663}
664
665static void
666sysv_calc(Elf *elf, GElf_Ehdr *elfhdr, GElf_Shdr *shdr)
667{
668	char *section_name;
669
670	section_name = elf_strptr(elf, elfhdr->e_shstrndx,
671	    (size_t) shdr->sh_name);
672	if ((shdr->sh_type == SHT_SYMTAB ||
673	    shdr->sh_type == SHT_STRTAB || shdr->sh_type == SHT_RELA ||
674	    shdr->sh_type == SHT_REL) && shdr->sh_addr == 0)
675		return;
676	tbl_append();
677	tbl_print(section_name, 0);
678	tbl_print_num(shdr->sh_size, radix, 1);
679	tbl_print_num(shdr->sh_addr, radix, 2);
680	text_size_total += shdr->sh_size;
681}
682
683static void
684sysv_footer(void)
685{
686	tbl_append();
687	tbl_print("Total", 0);
688	tbl_print_num(text_size_total, radix, 1);
689	tbl_flush();
690	putchar('\n');
691}
692
693/*
694 * berkeley style output formatting helper functions.
695 */
696static void
697berkeley_header(void)
698{
699	static int printed;
700
701	text_size = data_size = bss_size = 0;
702	if (!printed) {
703		tbl_new(6);
704		tbl_append();
705		tbl_print("text", 0);
706		tbl_print("data", 1);
707		tbl_print("bss", 2);
708		if (radix == RADIX_OCTAL)
709			tbl_print("oct", 3);
710		else
711			tbl_print("dec", 3);
712		tbl_print("hex", 4);
713		tbl_print("filename", 5);
714		printed = 1;
715	}
716}
717
718static void
719berkeley_calc(GElf_Shdr *shdr)
720{
721	if (shdr != NULL) {
722		if (!(shdr->sh_flags & SHF_ALLOC))
723			return;
724		if ((shdr->sh_flags & SHF_ALLOC) &&
725		    ((shdr->sh_flags & SHF_EXECINSTR) ||
726		    !(shdr->sh_flags & SHF_WRITE)))
727			text_size += shdr->sh_size;
728		else if ((shdr->sh_flags & SHF_ALLOC) &&
729		    (shdr->sh_flags & SHF_WRITE) &&
730		    (shdr->sh_type != SHT_NOBITS))
731			data_size += shdr->sh_size;
732		else
733			bss_size += shdr->sh_size;
734	}
735}
736
737static void
738berkeley_totals(void)
739{
740	long unsigned int grand_total;
741
742	grand_total = text_size_total + data_size_total + bss_size_total;
743	tbl_append();
744	tbl_print_num(text_size_total, radix, 0);
745	tbl_print_num(data_size_total, radix, 1);
746	tbl_print_num(bss_size_total, radix, 2);
747	if (radix == RADIX_OCTAL)
748		tbl_print_num(grand_total, RADIX_OCTAL, 3);
749	else
750		tbl_print_num(grand_total, RADIX_DECIMAL, 3);
751	tbl_print_num(grand_total, RADIX_HEX, 4);
752}
753
754static void
755berkeley_footer(const char *name, const char *ar_name, const char *msg)
756{
757	char buf[BUF_SIZE];
758
759	total_size = text_size + data_size + bss_size;
760	if (show_totals) {
761		text_size_total += text_size;
762		bss_size_total += bss_size;
763		data_size_total += data_size;
764	}
765
766	tbl_append();
767	tbl_print_num(text_size, radix, 0);
768	tbl_print_num(data_size, radix, 1);
769	tbl_print_num(bss_size, radix, 2);
770	if (radix == RADIX_OCTAL)
771		tbl_print_num(total_size, RADIX_OCTAL, 3);
772	else
773		tbl_print_num(total_size, RADIX_DECIMAL, 3);
774	tbl_print_num(total_size, RADIX_HEX, 4);
775	if (ar_name != NULL && name != NULL)
776		(void) snprintf(buf, BUF_SIZE, "%s (%s %s)", ar_name, msg,
777		    name);
778	else if (ar_name != NULL && name == NULL)
779		(void) snprintf(buf, BUF_SIZE, "%s (%s)", ar_name, msg);
780	else
781		(void) snprintf(buf, BUF_SIZE, "%s", name);
782	tbl_print(buf, 5);
783}
784
785
786static void
787tbl_new(int col)
788{
789
790	assert(tb == NULL);
791	assert(col > 0);
792	if ((tb = calloc(1, sizeof(*tb))) == NULL)
793		err(EXIT_FAILURE, "calloc");
794	if ((tb->tbl = calloc(col, sizeof(*tb->tbl))) == NULL)
795		err(EXIT_FAILURE, "calloc");
796	if ((tb->width = calloc(col, sizeof(*tb->width))) == NULL)
797		err(EXIT_FAILURE, "calloc");
798	tb->col = col;
799	tb->row = 0;
800}
801
802static void
803tbl_print(const char *s, int col)
804{
805	int len;
806
807	assert(tb != NULL && tb->col > 0 && tb->row > 0 && col < tb->col);
808	assert(s != NULL && tb->tbl[col][tb->row - 1] == NULL);
809	if ((tb->tbl[col][tb->row - 1] = strdup(s)) == NULL)
810		err(EXIT_FAILURE, "strdup");
811	len = strlen(s);
812	if (len > tb->width[col])
813		tb->width[col] = len;
814}
815
816static void
817tbl_print_num(uint64_t num, enum radix_style rad, int col)
818{
819	char buf[BUF_SIZE];
820
821	(void) snprintf(buf, BUF_SIZE, (rad == RADIX_DECIMAL ? "%ju" :
822	    ((rad == RADIX_OCTAL) ? "0%jo" : "0x%jx")), (uintmax_t) num);
823	tbl_print(buf, col);
824}
825
826static void
827tbl_append(void)
828{
829	int i;
830
831	assert(tb != NULL && tb->col > 0);
832	tb->row++;
833	for (i = 0; i < tb->col; i++) {
834		tb->tbl[i] = realloc(tb->tbl[i], sizeof(*tb->tbl[i]) * tb->row);
835		if (tb->tbl[i] == NULL)
836			err(EXIT_FAILURE, "realloc");
837		tb->tbl[i][tb->row - 1] = NULL;
838	}
839}
840
841static void
842tbl_flush(void)
843{
844	const char *str;
845	int i, j;
846
847	if (tb == NULL)
848		return;
849
850	assert(tb->col > 0);
851	for (i = 0; i < tb->row; i++) {
852		if (style == STYLE_BERKELEY)
853			printf("  ");
854		for (j = 0; j < tb->col; j++) {
855			str = (tb->tbl[j][i] != NULL ? tb->tbl[j][i] : "");
856			if (style == STYLE_SYSV && j == 0)
857				printf("%-*s", tb->width[j], str);
858			else if (style == STYLE_BERKELEY && j == tb->col - 1)
859				printf("%s", str);
860			else
861				printf("%*s", tb->width[j], str);
862			if (j == tb->col -1)
863				putchar('\n');
864			else
865				printf("   ");
866		}
867	}
868
869	for (i = 0; i < tb->col; i++) {
870		for (j = 0; j < tb->row; j++) {
871			if (tb->tbl[i][j])
872				free(tb->tbl[i][j]);
873		}
874		free(tb->tbl[i]);
875	}
876	free(tb->tbl);
877	free(tb->width);
878	free(tb);
879	tb = NULL;
880}
881
882#define	USAGE_MESSAGE	"\
883Usage: %s [options] file ...\n\
884  Display sizes of ELF sections.\n\n\
885  Options:\n\
886  --format=format    Display output in specified format.  Supported\n\
887                     values are `berkeley' and `sysv'.\n\
888  --help             Display this help message and exit.\n\
889  --radix=radix      Display numeric values in the specified radix.\n\
890                     Supported values are: 8, 10 and 16.\n\
891  --totals           Show cumulative totals of section sizes.\n\
892  --version          Display a version identifier and exit.\n\
893  -A                 Equivalent to `--format=sysv'.\n\
894  -B                 Equivalent to `--format=berkeley'.\n\
895  -V                 Equivalent to `--version'.\n\
896  -d                 Equivalent to `--radix=10'.\n\
897  -h                 Same as option --help.\n\
898  -o                 Equivalent to `--radix=8'.\n\
899  -t                 Equivalent to option --totals.\n\
900  -x                 Equivalent to `--radix=16'.\n"
901
902static void
903usage(void)
904{
905	(void) fprintf(stderr, USAGE_MESSAGE, ELFTC_GETPROGNAME());
906	exit(EXIT_FAILURE);
907}
908
909static void
910show_version(void)
911{
912	(void) printf("%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version());
913	exit(EXIT_SUCCESS);
914}
915