xref: /netbsd-src/usr.bin/stat/stat.c (revision a536ee5124e62c9a0051a252f7833dc8f50f44c9)
1 /*	$NetBSD: stat.c,v 1.37 2012/12/02 21:13:07 erh Exp $ */
2 
3 /*
4  * Copyright (c) 2002-2011 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Andrew Brown.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #if HAVE_NBTOOL_CONFIG_H
33 #include "nbtool_config.h"
34 #endif
35 
36 #include <sys/cdefs.h>
37 #if !defined(lint)
38 __RCSID("$NetBSD: stat.c,v 1.37 2012/12/02 21:13:07 erh Exp $");
39 #endif
40 
41 #if ! HAVE_NBTOOL_CONFIG_H
42 #define HAVE_STRUCT_STAT_ST_FLAGS 1
43 #define HAVE_STRUCT_STAT_ST_GEN 1
44 #define HAVE_STRUCT_STAT_ST_BIRTHTIME 1
45 #define HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC 1
46 #define HAVE_STRUCT_STAT_ST_MTIMENSEC 1
47 #define HAVE_DEVNAME 1
48 #endif /* HAVE_NBTOOL_CONFIG_H */
49 
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 
53 #include <ctype.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <grp.h>
57 #include <limits.h>
58 #include <pwd.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <time.h>
63 #include <unistd.h>
64 #include <vis.h>
65 
66 #if HAVE_STRUCT_STAT_ST_FLAGS
67 #define DEF_F "%#Xf "
68 #define RAW_F "%f "
69 #define SHELL_F " st_flags=%f"
70 #else /* HAVE_STRUCT_STAT_ST_FLAGS */
71 #define DEF_F
72 #define RAW_F
73 #define SHELL_F
74 #endif /* HAVE_STRUCT_STAT_ST_FLAGS */
75 
76 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
77 #define DEF_B "\"%SB\" "
78 #define RAW_B "%B "
79 #define SHELL_B "st_birthtime=%SB "
80 #else /* HAVE_STRUCT_STAT_ST_BIRTHTIME */
81 #define DEF_B
82 #define RAW_B
83 #define SHELL_B
84 #endif /* HAVE_STRUCT_STAT_ST_BIRTHTIME */
85 
86 #if HAVE_STRUCT_STAT_ST_ATIM
87 #define st_atimespec st_atim
88 #define st_ctimespec st_ctim
89 #define st_mtimespec st_mtim
90 #endif /* HAVE_STRUCT_STAT_ST_ATIM */
91 
92 #define DEF_FORMAT \
93 	"%d %i %Sp %l %Su %Sg %r %z \"%Sa\" \"%Sm\" \"%Sc\" " DEF_B \
94 	"%k %b " DEF_F "%N"
95 #define RAW_FORMAT	"%d %i %#p %l %u %g %r %z %a %m %c " RAW_B \
96 	"%k %b " RAW_F "%N"
97 #define LS_FORMAT	"%Sp %l %Su %Sg %Z %Sm %N%SY"
98 #define LSF_FORMAT	"%Sp %l %Su %Sg %Z %Sm %N%T%SY"
99 #define SHELL_FORMAT \
100 	"st_dev=%d st_ino=%i st_mode=%#p st_nlink=%l " \
101 	"st_uid=%u st_gid=%g st_rdev=%r st_size=%z " \
102 	"st_atime=%Sa st_mtime=%Sm st_ctime=%Sc " SHELL_B \
103 	"st_blksize=%k st_blocks=%b" SHELL_F
104 #define LINUX_FORMAT \
105 	"  File: \"%N\"%n" \
106 	"  Size: %-11z  FileType: %HT%n" \
107 	"  Mode: (%04OLp/%.10Sp)         Uid: (%5u/%8Su)  Gid: (%5g/%8Sg)%n" \
108 	"Device: %Hd,%Ld   Inode: %i    Links: %l%n" \
109 	"Access: %Sa%n" \
110 	"Modify: %Sm%n" \
111 	"Change: %Sc"
112 
113 #define TIME_FORMAT	"%b %e %T %Y"
114 
115 #define FLAG_POUND	0x01
116 #define FLAG_SPACE	0x02
117 #define FLAG_PLUS	0x04
118 #define FLAG_ZERO	0x08
119 #define FLAG_MINUS	0x10
120 
121 /*
122  * These format characters must all be unique, except the magic one.
123  */
124 #define FMT_MAGIC	'%'
125 #define FMT_DOT		'.'
126 
127 #define SIMPLE_NEWLINE	'n'
128 #define SIMPLE_TAB	't'
129 #define SIMPLE_PERCENT	'%'
130 #define SIMPLE_NUMBER	'@'
131 
132 #define FMT_POUND	'#'
133 #define FMT_SPACE	' '
134 #define FMT_PLUS	'+'
135 #define FMT_ZERO	'0'
136 #define FMT_MINUS	'-'
137 
138 #define FMT_DECIMAL 	'D'
139 #define FMT_OCTAL 	'O'
140 #define FMT_UNSIGNED 	'U'
141 #define FMT_HEX 	'X'
142 #define FMT_FLOAT 	'F'
143 #define FMT_STRING 	'S'
144 
145 #define FMTF_DECIMAL	0x01
146 #define FMTF_OCTAL	0x02
147 #define FMTF_UNSIGNED	0x04
148 #define FMTF_HEX	0x08
149 #define FMTF_FLOAT	0x10
150 #define FMTF_STRING	0x20
151 
152 #define HIGH_PIECE	'H'
153 #define MIDDLE_PIECE	'M'
154 #define LOW_PIECE	'L'
155 
156 #define	SHOW_realpath	'R'
157 #define SHOW_st_dev	'd'
158 #define SHOW_st_ino	'i'
159 #define SHOW_st_mode	'p'
160 #define SHOW_st_nlink	'l'
161 #define SHOW_st_uid	'u'
162 #define SHOW_st_gid	'g'
163 #define SHOW_st_rdev	'r'
164 #define SHOW_st_atime	'a'
165 #define SHOW_st_mtime	'm'
166 #define SHOW_st_ctime	'c'
167 #define SHOW_st_btime	'B'
168 #define SHOW_st_size	'z'
169 #define SHOW_st_blocks	'b'
170 #define SHOW_st_blksize	'k'
171 #define SHOW_st_flags	'f'
172 #define SHOW_st_gen	'v'
173 #define SHOW_symlink	'Y'
174 #define SHOW_filetype	'T'
175 #define SHOW_filename	'N'
176 #define SHOW_sizerdev	'Z'
177 
178 static void	usage(const char *) __dead;
179 static void	output(const struct stat *, const char *,
180 	    const char *, int, int, int);
181 static int	format1(const struct stat *,	/* stat info */
182 	    const char *,		/* the file name */
183 	    const char *, int,		/* the format string itself */
184 	    char *, size_t,		/* a place to put the output */
185 	    int, int, int, int,		/* the parsed format */
186 	    int, int, int);
187 
188 static const char *timefmt;
189 static int linkfail;
190 
191 #define addchar(s, c, nl) \
192 	do { \
193 		(void)fputc((c), (s)); \
194 		(*nl) = ((c) == '\n'); \
195 	} while (0/*CONSTCOND*/)
196 
197 int
198 main(int argc, char *argv[])
199 {
200 	struct stat st;
201 	int ch, rc, errs, am_readlink;
202 	int lsF, fmtchar, usestat, fn, nonl, quiet;
203 	const char *statfmt, *options, *synopsis;
204 
205 	am_readlink = 0;
206 	lsF = 0;
207 	fmtchar = '\0';
208 	usestat = 0;
209 	nonl = 0;
210 	quiet = 0;
211 	linkfail = 0;
212 	statfmt = NULL;
213 	timefmt = NULL;
214 
215 	setprogname(argv[0]);
216 
217 	if (strcmp(getprogname(), "readlink") == 0) {
218 		am_readlink = 1;
219 		options = "fnqsv";
220 		synopsis = "[-fnqsv] [file ...]";
221 		statfmt = "%Y";
222 		fmtchar = 'f';
223 		quiet = 1;
224 	} else {
225 		options = "f:FlLnqrst:x";
226 		synopsis = "[-FlLnqrsx] [-f format] [-t timefmt] [file ...]";
227 	}
228 
229 	while ((ch = getopt(argc, argv, options)) != -1)
230 		switch (ch) {
231 		case 'F':
232 			lsF = 1;
233 			break;
234 		case 'L':
235 			usestat = 1;
236 			break;
237 		case 'n':
238 			nonl = 1;
239 			break;
240 		case 'q':
241 			quiet = 1;
242 			break;
243 		case 'f':
244 			if (am_readlink) {
245 				statfmt = "%R";
246 				break;
247 			}
248 			statfmt = optarg;
249 			/* FALLTHROUGH */
250 		case 'l':
251 		case 'r':
252 		case 's':
253 			if (am_readlink) {
254 				quiet = 1;
255 				break;
256 			}
257 			/*FALLTHROUGH*/
258 		case 'x':
259 			if (fmtchar != 0)
260 				errx(1, "can't use format '%c' with '%c'",
261 				    fmtchar, ch);
262 			fmtchar = ch;
263 			break;
264 		case 't':
265 			timefmt = optarg;
266 			break;
267 		case 'v':
268 			quiet = 0;
269 			break;
270 		default:
271 			usage(synopsis);
272 		}
273 
274 	argc -= optind;
275 	argv += optind;
276 	fn = 1;
277 
278 	if (fmtchar == '\0') {
279 		if (lsF)
280 			fmtchar = 'l';
281 		else {
282 			fmtchar = 'f';
283 			statfmt = DEF_FORMAT;
284 		}
285 	}
286 
287 	if (lsF && fmtchar != 'l')
288 		errx(1, "can't use format '%c' with -F", fmtchar);
289 
290 	switch (fmtchar) {
291 	case 'f':
292 		/* statfmt already set */
293 		break;
294 	case 'l':
295 		statfmt = lsF ? LSF_FORMAT : LS_FORMAT;
296 		break;
297 	case 'r':
298 		statfmt = RAW_FORMAT;
299 		break;
300 	case 's':
301 		statfmt = SHELL_FORMAT;
302 		if (timefmt == NULL)
303 			timefmt = "%s";
304 		break;
305 	case 'x':
306 		statfmt = LINUX_FORMAT;
307 		if (timefmt == NULL)
308 			timefmt = "%c";
309 		break;
310 	default:
311 		usage(synopsis);
312 		/*NOTREACHED*/
313 	}
314 
315 	if (timefmt == NULL)
316 		timefmt = TIME_FORMAT;
317 
318 	errs = 0;
319 	do {
320 		if (argc == 0)
321 			rc = fstat(STDIN_FILENO, &st);
322 		else if (usestat) {
323 			/*
324 			 * Try stat() and if it fails, fall back to
325 			 * lstat() just in case we're examining a
326 			 * broken symlink.
327 			 */
328 			if ((rc = stat(argv[0], &st)) == -1 &&
329 			    errno == ENOENT &&
330 			    (rc = lstat(argv[0], &st)) == -1)
331 				errno = ENOENT;
332 		}
333 		else
334 			rc = lstat(argv[0], &st);
335 
336 		if (rc == -1) {
337 			errs = 1;
338 			linkfail = 1;
339 			if (!quiet)
340 				warn("%s: %s",
341 				    argc == 0 ? "(stdin)" : argv[0],
342 				    usestat ? "stat" : "lstat");
343 		}
344 		else
345 			output(&st, argv[0], statfmt, fn, nonl, quiet);
346 
347 		argv++;
348 		argc--;
349 		fn++;
350 	} while (argc > 0);
351 
352 	return (am_readlink ? linkfail : errs);
353 }
354 
355 static void
356 usage(const char *synopsis)
357 {
358 
359 	(void)fprintf(stderr, "usage: %s %s\n", getprogname(), synopsis);
360 	exit(1);
361 }
362 
363 /*
364  * Parses a format string.
365  */
366 static void
367 output(const struct stat *st, const char *file,
368     const char *statfmt, int fn, int nonl, int quiet)
369 {
370 	int flags, size, prec, ofmt, hilo, what;
371 	/*
372 	 * buf size is enough for an item of length PATH_MAX,
373 	 * multiplied by 4 for vis encoding, plus 4 for symlink
374 	 * " -> " prefix, plus 1 for \0 terminator.
375 	 */
376 	char buf[PATH_MAX * 4 + 4 + 1];
377 	const char *subfmt;
378 	int nl, t, i;
379 
380 	nl = 1;
381 	while (*statfmt != '\0') {
382 
383 		/*
384 		 * Non-format characters go straight out.
385 		 */
386 		if (*statfmt != FMT_MAGIC) {
387 			addchar(stdout, *statfmt, &nl);
388 			statfmt++;
389 			continue;
390 		}
391 
392 		/*
393 		 * The current format "substring" starts here,
394 		 * and then we skip the magic.
395 		 */
396 		subfmt = statfmt;
397 		statfmt++;
398 
399 		/*
400 		 * Some simple one-character "formats".
401 		 */
402 		switch (*statfmt) {
403 		case SIMPLE_NEWLINE:
404 			addchar(stdout, '\n', &nl);
405 			statfmt++;
406 			continue;
407 		case SIMPLE_TAB:
408 			addchar(stdout, '\t', &nl);
409 			statfmt++;
410 			continue;
411 		case SIMPLE_PERCENT:
412 			addchar(stdout, '%', &nl);
413 			statfmt++;
414 			continue;
415 		case SIMPLE_NUMBER: {
416 			char num[12], *p;
417 
418 			snprintf(num, sizeof(num), "%d", fn);
419 			for (p = &num[0]; *p; p++)
420 				addchar(stdout, *p, &nl);
421 			statfmt++;
422 			continue;
423 		}
424 		}
425 
426 		/*
427 		 * This must be an actual format string.  Format strings are
428 		 * similar to printf(3) formats up to a point, and are of
429 		 * the form:
430 		 *
431 		 *	%	required start of format
432 		 *	[-# +0]	opt. format characters
433 		 *	size	opt. field width
434 		 *	.	opt. decimal separator, followed by
435 		 *	prec	opt. precision
436 		 *	fmt	opt. output specifier (string, numeric, etc.)
437 		 *	sub	opt. sub field specifier (high, middle, low)
438 		 *	datum	required field specifier (size, mode, etc)
439 		 *
440 		 * Only the % and the datum selector are required.  All data
441 		 * have reasonable default output forms.  The "sub" specifier
442 		 * only applies to certain data (mode, dev, rdev, filetype).
443 		 * The symlink output defaults to STRING, yet will only emit
444 		 * the leading " -> " if STRING is explicitly specified.  The
445 		 * sizerdev datum will generate rdev output for character or
446 		 * block devices, and size output for all others.
447 		 * For STRING output, the # format requests vis encoding.
448 		 */
449 		flags = 0;
450 		do {
451 			if      (*statfmt == FMT_POUND)
452 				flags |= FLAG_POUND;
453 			else if (*statfmt == FMT_SPACE)
454 				flags |= FLAG_SPACE;
455 			else if (*statfmt == FMT_PLUS)
456 				flags |= FLAG_PLUS;
457 			else if (*statfmt == FMT_ZERO)
458 				flags |= FLAG_ZERO;
459 			else if (*statfmt == FMT_MINUS)
460 				flags |= FLAG_MINUS;
461 			else
462 				break;
463 			statfmt++;
464 		} while (1/*CONSTCOND*/);
465 
466 		size = -1;
467 		if (isdigit((unsigned)*statfmt)) {
468 			size = 0;
469 			while (isdigit((unsigned)*statfmt)) {
470 				size = (size * 10) + (*statfmt - '0');
471 				statfmt++;
472 				if (size < 0)
473 					goto badfmt;
474 			}
475 		}
476 
477 		prec = -1;
478 		if (*statfmt == FMT_DOT) {
479 			statfmt++;
480 
481 			prec = 0;
482 			while (isdigit((unsigned)*statfmt)) {
483 				prec = (prec * 10) + (*statfmt - '0');
484 				statfmt++;
485 				if (prec < 0)
486 					goto badfmt;
487 			}
488 		}
489 
490 #define fmtcase(x, y)		case (y): (x) = (y); statfmt++; break
491 #define fmtcasef(x, y, z)	case (y): (x) = (z); statfmt++; break
492 		switch (*statfmt) {
493 			fmtcasef(ofmt, FMT_DECIMAL,	FMTF_DECIMAL);
494 			fmtcasef(ofmt, FMT_OCTAL,	FMTF_OCTAL);
495 			fmtcasef(ofmt, FMT_UNSIGNED,	FMTF_UNSIGNED);
496 			fmtcasef(ofmt, FMT_HEX,		FMTF_HEX);
497 			fmtcasef(ofmt, FMT_FLOAT,	FMTF_FLOAT);
498 			fmtcasef(ofmt, FMT_STRING,	FMTF_STRING);
499 		default:
500 			ofmt = 0;
501 			break;
502 		}
503 
504 		switch (*statfmt) {
505 			fmtcase(hilo, HIGH_PIECE);
506 			fmtcase(hilo, MIDDLE_PIECE);
507 			fmtcase(hilo, LOW_PIECE);
508 		default:
509 			hilo = 0;
510 			break;
511 		}
512 
513 		switch (*statfmt) {
514 			fmtcase(what, SHOW_realpath);
515 			fmtcase(what, SHOW_st_dev);
516 			fmtcase(what, SHOW_st_ino);
517 			fmtcase(what, SHOW_st_mode);
518 			fmtcase(what, SHOW_st_nlink);
519 			fmtcase(what, SHOW_st_uid);
520 			fmtcase(what, SHOW_st_gid);
521 			fmtcase(what, SHOW_st_rdev);
522 			fmtcase(what, SHOW_st_atime);
523 			fmtcase(what, SHOW_st_mtime);
524 			fmtcase(what, SHOW_st_ctime);
525 			fmtcase(what, SHOW_st_btime);
526 			fmtcase(what, SHOW_st_size);
527 			fmtcase(what, SHOW_st_blocks);
528 			fmtcase(what, SHOW_st_blksize);
529 			fmtcase(what, SHOW_st_flags);
530 			fmtcase(what, SHOW_st_gen);
531 			fmtcase(what, SHOW_symlink);
532 			fmtcase(what, SHOW_filetype);
533 			fmtcase(what, SHOW_filename);
534 			fmtcase(what, SHOW_sizerdev);
535 		default:
536 			goto badfmt;
537 		}
538 #undef fmtcasef
539 #undef fmtcase
540 
541 		t = format1(st,
542 		     file,
543 		     subfmt, statfmt - subfmt,
544 		     buf, sizeof(buf),
545 		     flags, size, prec, ofmt, hilo, what, quiet);
546 
547 		for (i = 0; i < t && i < (int)(sizeof(buf) - 1); i++)
548 			addchar(stdout, buf[i], &nl);
549 
550 		continue;
551 
552 	badfmt:
553 		errx(1, "%.*s: bad format",
554 		    (int)(statfmt - subfmt + 1), subfmt);
555 	}
556 
557 	if (!nl && !nonl)
558 		(void)fputc('\n', stdout);
559 	(void)fflush(stdout);
560 }
561 
562 /*
563  * Arranges output according to a single parsed format substring.
564  */
565 static int
566 format1(const struct stat *st,
567     const char *file,
568     const char *fmt, int flen,
569     char *buf, size_t blen,
570     int flags, int size, int prec, int ofmt,
571     int hilo, int what, int quiet)
572 {
573 	u_int64_t data;
574 	char *stmp, lfmt[24], tmp[20];
575 	const char *sdata;
576 	char smode[12], sid[12], path[PATH_MAX + 4], visbuf[PATH_MAX * 4 + 4];
577 	struct passwd *pw;
578 	struct group *gr;
579 	struct tm *tm;
580 	time_t secs;
581 	long nsecs;
582 	int l;
583 	int formats;	/* bitmap of allowed formats for this datum */
584 	int small;	/* true if datum is a small integer */
585 	int gottime;	/* true if secs and nsecs are valid */
586 	int shift;	/* powers of 2 to scale numbers before printing */
587 	size_t prefixlen; /* length of constant prefix for string data */
588 
589 	formats = 0;
590 	small = 0;
591 	gottime = 0;
592 	secs = 0;
593 	nsecs = 0;
594 	shift = 0;
595 	prefixlen = 0;
596 
597 	/*
598 	 * First, pick out the data and tweak it based on hilo or
599 	 * specified output format (symlink output only).
600 	 */
601 	switch (what) {
602 	case SHOW_st_dev:
603 	case SHOW_st_rdev:
604 		small = (sizeof(st->st_dev) == 4);
605 		data = (what == SHOW_st_dev) ? st->st_dev : st->st_rdev;
606 #if HAVE_DEVNAME
607 		sdata = (what == SHOW_st_dev) ?
608 		    devname(st->st_dev, S_IFBLK) :
609 		    devname(st->st_rdev,
610 		    S_ISCHR(st->st_mode) ? S_IFCHR :
611 		    S_ISBLK(st->st_mode) ? S_IFBLK :
612 		    0U);
613 		if (sdata == NULL)
614 			sdata = "???";
615 #endif /* HAVE_DEVNAME */
616 		if (hilo == HIGH_PIECE) {
617 			data = major(data);
618 			hilo = 0;
619 		}
620 		else if (hilo == LOW_PIECE) {
621 			data = minor((unsigned)data);
622 			hilo = 0;
623 		}
624 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX |
625 #if HAVE_DEVNAME
626 		    FMTF_STRING;
627 #else /* HAVE_DEVNAME */
628 		    0;
629 #endif /* HAVE_DEVNAME */
630 		if (ofmt == 0)
631 			ofmt = FMTF_UNSIGNED;
632 		break;
633 	case SHOW_st_ino:
634 		small = (sizeof(st->st_ino) == 4);
635 		data = st->st_ino;
636 		sdata = NULL;
637 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
638 		if (ofmt == 0)
639 			ofmt = FMTF_UNSIGNED;
640 		break;
641 	case SHOW_st_mode:
642 		small = (sizeof(st->st_mode) == 4);
643 		data = st->st_mode;
644 		strmode(st->st_mode, smode);
645 		stmp = smode;
646 		l = strlen(stmp);
647 		if (stmp[l - 1] == ' ')
648 			stmp[--l] = '\0';
649 		if (hilo == HIGH_PIECE) {
650 			data >>= 12;
651 			stmp += 1;
652 			stmp[3] = '\0';
653 			hilo = 0;
654 		}
655 		else if (hilo == MIDDLE_PIECE) {
656 			data = (data >> 9) & 07;
657 			stmp += 4;
658 			stmp[3] = '\0';
659 			hilo = 0;
660 		}
661 		else if (hilo == LOW_PIECE) {
662 			data &= 0777;
663 			stmp += 7;
664 			stmp[3] = '\0';
665 			hilo = 0;
666 		}
667 		sdata = stmp;
668 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX |
669 		    FMTF_STRING;
670 		if (ofmt == 0)
671 			ofmt = FMTF_OCTAL;
672 		break;
673 	case SHOW_st_nlink:
674 		small = (sizeof(st->st_dev) == 4);
675 		data = st->st_nlink;
676 		sdata = NULL;
677 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
678 		if (ofmt == 0)
679 			ofmt = FMTF_UNSIGNED;
680 		break;
681 	case SHOW_st_uid:
682 		small = (sizeof(st->st_uid) == 4);
683 		data = st->st_uid;
684 		if ((pw = getpwuid(st->st_uid)) != NULL)
685 			sdata = pw->pw_name;
686 		else {
687 			snprintf(sid, sizeof(sid), "(%ld)", (long)st->st_uid);
688 			sdata = sid;
689 		}
690 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX |
691 		    FMTF_STRING;
692 		if (ofmt == 0)
693 			ofmt = FMTF_UNSIGNED;
694 		break;
695 	case SHOW_st_gid:
696 		small = (sizeof(st->st_gid) == 4);
697 		data = st->st_gid;
698 		if ((gr = getgrgid(st->st_gid)) != NULL)
699 			sdata = gr->gr_name;
700 		else {
701 			snprintf(sid, sizeof(sid), "(%ld)", (long)st->st_gid);
702 			sdata = sid;
703 		}
704 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX |
705 		    FMTF_STRING;
706 		if (ofmt == 0)
707 			ofmt = FMTF_UNSIGNED;
708 		break;
709 	case SHOW_st_atime:
710 		gottime = 1;
711 		secs = st->st_atime;
712 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
713 		nsecs = st->st_atimensec;
714 #endif
715 		/* FALLTHROUGH */
716 	case SHOW_st_mtime:
717 		if (!gottime) {
718 			gottime = 1;
719 			secs = st->st_mtime;
720 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
721 			nsecs = st->st_mtimensec;
722 #endif
723 		}
724 		/* FALLTHROUGH */
725 	case SHOW_st_ctime:
726 		if (!gottime) {
727 			gottime = 1;
728 			secs = st->st_ctime;
729 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
730 			nsecs = st->st_ctimensec;
731 #endif
732 		}
733 		/* FALLTHROUGH */
734 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
735 	case SHOW_st_btime:
736 		if (!gottime) {
737 			gottime = 1;
738 			secs = st->st_birthtime;
739 #if HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC
740 			nsecs = st->st_birthtimensec;
741 #endif /* HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC */
742 		}
743 #endif /* HAVE_STRUCT_STAT_ST_BIRTHTIME */
744 		small = (sizeof(secs) == 4);
745 		data = secs;
746 		tm = localtime(&secs);
747 		if (tm == NULL) {
748 			secs = 0;
749 			tm = localtime(&secs);
750 		}
751 		(void)strftime(path, sizeof(path), timefmt, tm);
752 		sdata = path;
753 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX |
754 		    FMTF_FLOAT | FMTF_STRING;
755 		if (ofmt == 0)
756 			ofmt = FMTF_DECIMAL;
757 		break;
758 	case SHOW_st_size:
759 		small = (sizeof(st->st_size) == 4);
760 		data = st->st_size;
761 		sdata = NULL;
762 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
763 		if (ofmt == 0)
764 			ofmt = FMTF_UNSIGNED;
765 		switch (hilo) {
766 		case HIGH_PIECE:
767 			shift = 30;	/* gigabytes */
768 			hilo = 0;
769 			break;
770 		case MIDDLE_PIECE:
771 			shift = 20;	/* megabytes */
772 			hilo = 0;
773 			break;
774 		case LOW_PIECE:
775 			shift = 10;	/* kilobytes */
776 			hilo = 0;
777 			break;
778 		}
779 		break;
780 	case SHOW_st_blocks:
781 		small = (sizeof(st->st_blocks) == 4);
782 		data = st->st_blocks;
783 		sdata = NULL;
784 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
785 		if (ofmt == 0)
786 			ofmt = FMTF_UNSIGNED;
787 		break;
788 	case SHOW_st_blksize:
789 		small = (sizeof(st->st_blksize) == 4);
790 		data = st->st_blksize;
791 		sdata = NULL;
792 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
793 		if (ofmt == 0)
794 			ofmt = FMTF_UNSIGNED;
795 		break;
796 #if HAVE_STRUCT_STAT_ST_FLAGS
797 	case SHOW_st_flags:
798 		small = (sizeof(st->st_flags) == 4);
799 		data = st->st_flags;
800 		sdata = NULL;
801 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
802 		if (ofmt == 0)
803 			ofmt = FMTF_UNSIGNED;
804 		break;
805 #endif /* HAVE_STRUCT_STAT_ST_FLAGS */
806 #if HAVE_STRUCT_STAT_ST_GEN
807 	case SHOW_st_gen:
808 		small = (sizeof(st->st_gen) == 4);
809 		data = st->st_gen;
810 		sdata = NULL;
811 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
812 		if (ofmt == 0)
813 			ofmt = FMTF_UNSIGNED;
814 		break;
815 #endif /* HAVE_STRUCT_STAT_ST_GEN */
816 	case SHOW_realpath:
817 		small = 0;
818 		data = 0;
819 		if (file == NULL) {
820 			(void)strlcpy(path, "(stdin)", sizeof(path));
821 			sdata = path;
822 		} else {
823 			snprintf(path, sizeof(path), " -> ");
824 			if (realpath(file, path + 4) == NULL) {
825 				if (!quiet)
826 					warn("realpath `%s'", file);
827 				linkfail = 1;
828 				l = 0;
829 				path[0] = '\0';
830 			}
831 			sdata = path + (ofmt == FMTF_STRING ? 0 : 4);
832 			prefixlen = (ofmt == FMTF_STRING ? 4 : 0);
833 		}
834 
835 		formats = FMTF_STRING;
836 		if (ofmt == 0)
837 			ofmt = FMTF_STRING;
838 		break;
839 	case SHOW_symlink:
840 		small = 0;
841 		data = 0;
842 		if (S_ISLNK(st->st_mode)) {
843 			snprintf(path, sizeof(path), " -> ");
844 			l = readlink(file, path + 4, sizeof(path) - 4 - 1);
845 			if (l == -1) {
846 				if (!quiet)
847 					warn("readlink `%s'", file);
848 				linkfail = 1;
849 				l = 0;
850 				path[0] = '\0';
851 			}
852 			path[l + 4] = '\0';
853 			sdata = path + (ofmt == FMTF_STRING ? 0 : 4);
854 			prefixlen = (ofmt == FMTF_STRING ? 4 : 0);
855 		}
856 		else {
857 			linkfail = 1;
858 			sdata = "";
859 		}
860 		formats = FMTF_STRING;
861 		if (ofmt == 0)
862 			ofmt = FMTF_STRING;
863 		break;
864 	case SHOW_filetype:
865 		small = 0;
866 		data = 0;
867 		sdata = "";
868 		if (hilo == 0 || hilo == LOW_PIECE) {
869 			switch (st->st_mode & S_IFMT) {
870 			case S_IFIFO:	sdata = "|";			break;
871 			case S_IFDIR:	sdata = "/";			break;
872 			case S_IFREG:
873 				if (st->st_mode &
874 				    (S_IXUSR | S_IXGRP | S_IXOTH))
875 					sdata = "*";
876 				break;
877 			case S_IFLNK:	sdata = "@";			break;
878 #ifdef S_IFSOCK
879 			case S_IFSOCK:	sdata = "=";			break;
880 #endif
881 #ifdef S_IFWHT
882 			case S_IFWHT:	sdata = "%";			break;
883 #endif /* S_IFWHT */
884 #ifdef S_IFDOOR
885 			case S_IFDOOR:	sdata = ">";			break;
886 #endif /* S_IFDOOR */
887 			}
888 			hilo = 0;
889 		}
890 		else if (hilo == HIGH_PIECE) {
891 			switch (st->st_mode & S_IFMT) {
892 			case S_IFIFO:	sdata = "Fifo File";		break;
893 			case S_IFCHR:	sdata = "Character Device";	break;
894 			case S_IFDIR:	sdata = "Directory";		break;
895 			case S_IFBLK:	sdata = "Block Device";		break;
896 			case S_IFREG:	sdata = "Regular File";		break;
897 			case S_IFLNK:	sdata = "Symbolic Link";	break;
898 #ifdef S_IFSOCK
899 			case S_IFSOCK:	sdata = "Socket";		break;
900 #endif
901 #ifdef S_IFWHT
902 			case S_IFWHT:	sdata = "Whiteout File";	break;
903 #endif /* S_IFWHT */
904 #ifdef S_IFDOOR
905 			case S_IFDOOR:	sdata = "Door";			break;
906 #endif /* S_IFDOOR */
907 			default:	sdata = "???";			break;
908 			}
909 			hilo = 0;
910 		}
911 		formats = FMTF_STRING;
912 		if (ofmt == 0)
913 			ofmt = FMTF_STRING;
914 		break;
915 	case SHOW_filename:
916 		small = 0;
917 		data = 0;
918 		if (file == NULL) {
919 			(void)strlcpy(path, "(stdin)", sizeof(path));
920 			if (hilo == HIGH_PIECE || hilo == LOW_PIECE)
921 				hilo = 0;
922 		}
923 		else if (hilo == 0)
924 			(void)strlcpy(path, file, sizeof(path));
925 		else {
926 			char *s;
927 			(void)strlcpy(path, file, sizeof(path));
928 			s = strrchr(path, '/');
929 			if (s != NULL) {
930 				/* trim off trailing /'s */
931 				while (s != path &&
932 				    s[0] == '/' && s[1] == '\0')
933 					*s-- = '\0';
934 				s = strrchr(path, '/');
935 			}
936 			if (hilo == HIGH_PIECE) {
937 				if (s == NULL)
938 					(void)strlcpy(path, ".", sizeof(path));
939 				else {
940 					while (s != path && s[0] == '/')
941 						*s-- = '\0';
942 				}
943 				hilo = 0;
944 			}
945 			else if (hilo == LOW_PIECE) {
946 				if (s != NULL && s[1] != '\0')
947 					(void)strlcpy(path, s + 1,
948 						      sizeof(path));
949 				hilo = 0;
950 			}
951 		}
952 		sdata = path;
953 		formats = FMTF_STRING;
954 		if (ofmt == 0)
955 			ofmt = FMTF_STRING;
956 		break;
957 	case SHOW_sizerdev:
958 		if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode)) {
959 			char majdev[20], mindev[20];
960 			int l1, l2;
961 
962 			l1 = format1(st,
963 			    file,
964 			    fmt, flen,
965 			    majdev, sizeof(majdev),
966 			    flags, size, prec,
967 			    ofmt, HIGH_PIECE, SHOW_st_rdev, quiet);
968 			l2 = format1(st,
969 			    file,
970 			    fmt, flen,
971 			    mindev, sizeof(mindev),
972 			    flags, size, prec,
973 			    ofmt, LOW_PIECE, SHOW_st_rdev, quiet);
974 			return (snprintf(buf, blen, "%.*s,%.*s",
975 			    l1, majdev, l2, mindev));
976 		}
977 		else {
978 			return (format1(st,
979 			    file,
980 			    fmt, flen,
981 			    buf, blen,
982 			    flags, size, prec,
983 			    ofmt, 0, SHOW_st_size, quiet));
984 		}
985 		/*NOTREACHED*/
986 	default:
987 		errx(1, "%.*s: bad format", (int)flen, fmt);
988 	}
989 
990 	/*
991 	 * If a subdatum was specified but not supported, or an output
992 	 * format was selected that is not supported, that's an error.
993 	 */
994 	if (hilo != 0 || (ofmt & formats) == 0)
995 		errx(1, "%.*s: bad format", (int)flen, fmt);
996 
997 	/*
998 	 * FLAG_POUND with FMTF_STRING means use vis(3) encoding.
999 	 * First prefixlen chars are not encoded.
1000 	 */
1001 	if ((flags & FLAG_POUND) != 0 && ofmt == FMTF_STRING) {
1002 		flags &= !FLAG_POUND;
1003 		strncpy(visbuf, sdata, prefixlen);
1004 		strnvis(visbuf + prefixlen, sizeof(visbuf) - prefixlen,
1005 		    sdata + prefixlen, VIS_WHITE | VIS_OCTAL | VIS_CSTYLE);
1006 		sdata = visbuf;
1007 	}
1008 
1009 	/*
1010 	 * Assemble the format string for passing to printf(3).
1011 	 */
1012 	lfmt[0] = '\0';
1013 	(void)strcat(lfmt, "%");
1014 	if (flags & FLAG_POUND)
1015 		(void)strcat(lfmt, "#");
1016 	if (flags & FLAG_SPACE)
1017 		(void)strcat(lfmt, " ");
1018 	if (flags & FLAG_PLUS)
1019 		(void)strcat(lfmt, "+");
1020 	if (flags & FLAG_MINUS)
1021 		(void)strcat(lfmt, "-");
1022 	if (flags & FLAG_ZERO)
1023 		(void)strcat(lfmt, "0");
1024 
1025 	/*
1026 	 * Only the timespecs support the FLOAT output format, and that
1027 	 * requires work that differs from the other formats.
1028 	 */
1029 	if (ofmt == FMTF_FLOAT) {
1030 		/*
1031 		 * Nothing after the decimal point, so just print seconds.
1032 		 */
1033 		if (prec == 0) {
1034 			if (size != -1) {
1035 				(void)snprintf(tmp, sizeof(tmp), "%d", size);
1036 				(void)strcat(lfmt, tmp);
1037 			}
1038 			(void)strcat(lfmt, "lld");
1039 			return (snprintf(buf, blen, lfmt,
1040 			    (long long)secs));
1041 		}
1042 
1043 		/*
1044 		 * Unspecified precision gets all the precision we have:
1045 		 * 9 digits.
1046 		 */
1047 		if (prec == -1)
1048 			prec = 9;
1049 
1050 		/*
1051 		 * Adjust the size for the decimal point and the digits
1052 		 * that will follow.
1053 		 */
1054 		size -= prec + 1;
1055 
1056 		/*
1057 		 * Any leftover size that's legitimate will be used.
1058 		 */
1059 		if (size > 0) {
1060 			(void)snprintf(tmp, sizeof(tmp), "%d", size);
1061 			(void)strcat(lfmt, tmp);
1062 		}
1063 		/* Seconds: time_t cast to long long. */
1064 		(void)strcat(lfmt, "lld");
1065 
1066 		/*
1067 		 * The stuff after the decimal point always needs zero
1068 		 * filling.
1069 		 */
1070 		(void)strcat(lfmt, ".%0");
1071 
1072 		/*
1073 		 * We can "print" at most nine digits of precision.  The
1074 		 * rest we will pad on at the end.
1075 		 *
1076 		 * Nanoseconds: long.
1077 		 */
1078 		(void)snprintf(tmp, sizeof(tmp), "%dld", prec > 9 ? 9 : prec);
1079 		(void)strcat(lfmt, tmp);
1080 
1081 		/*
1082 		 * For precision of less that nine digits, trim off the
1083 		 * less significant figures.
1084 		 */
1085 		for (; prec < 9; prec++)
1086 			nsecs /= 10;
1087 
1088 		/*
1089 		 * Use the format, and then tack on any zeroes that
1090 		 * might be required to make up the requested precision.
1091 		 */
1092 		l = snprintf(buf, blen, lfmt, (long long)secs, nsecs);
1093 		for (; prec > 9 && l < (int)blen; prec--, l++)
1094 			(void)strcat(buf, "0");
1095 		return (l);
1096 	}
1097 
1098 	/*
1099 	 * Add on size and precision, if specified, to the format.
1100 	 */
1101 	if (size != -1) {
1102 		(void)snprintf(tmp, sizeof(tmp), "%d", size);
1103 		(void)strcat(lfmt, tmp);
1104 	}
1105 	if (prec != -1) {
1106 		(void)snprintf(tmp, sizeof(tmp), ".%d", prec);
1107 		(void)strcat(lfmt, tmp);
1108 	}
1109 
1110 	/*
1111 	 * String output uses the temporary sdata.
1112 	 */
1113 	if (ofmt == FMTF_STRING) {
1114 		if (sdata == NULL)
1115 			errx(1, "%.*s: bad format", (int)flen, fmt);
1116 		(void)strcat(lfmt, "s");
1117 		return (snprintf(buf, blen, lfmt, sdata));
1118 	}
1119 
1120 	/*
1121 	 * Ensure that sign extension does not cause bad looking output
1122 	 * for some forms.
1123 	 */
1124 	if (small && ofmt != FMTF_DECIMAL)
1125 		data = (u_int32_t)data;
1126 
1127 	/*
1128 	 * The four "numeric" output forms.
1129 	 */
1130 	(void)strcat(lfmt, "ll");
1131 	switch (ofmt) {
1132 	case FMTF_DECIMAL:	(void)strcat(lfmt, "d");	break;
1133 	case FMTF_OCTAL:	(void)strcat(lfmt, "o");	break;
1134 	case FMTF_UNSIGNED:	(void)strcat(lfmt, "u");	break;
1135 	case FMTF_HEX:		(void)strcat(lfmt, "x");	break;
1136 	}
1137 
1138 	/*
1139 	 * shift and round to nearest for kilobytes, megabytes,
1140 	 * gigabytes.
1141 	 */
1142 	if (shift > 0) {
1143 		data >>= (shift - 1);
1144 		data++;
1145 		data >>= 1;
1146 	}
1147 
1148 	return (snprintf(buf, blen, lfmt, data));
1149 }
1150