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