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