xref: /freebsd/bin/ls/ls.c (revision 145992504973bd16cf3518af9ba5ce185fefa82a)
1 /*-
2  * Copyright (c) 1989, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Michael Fischbein.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1989, 1993, 1994\n\
36 	The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38 
39 #if 0
40 #ifndef lint
41 static char sccsid[] = "@(#)ls.c	8.5 (Berkeley) 4/2/94";
42 #endif /* not lint */
43 #endif
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include <sys/param.h>
48 #include <sys/stat.h>
49 #include <sys/ioctl.h>
50 #include <sys/mac.h>
51 
52 #include <dirent.h>
53 #include <err.h>
54 #include <errno.h>
55 #include <fts.h>
56 #include <grp.h>
57 #include <inttypes.h>
58 #include <limits.h>
59 #include <locale.h>
60 #include <pwd.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65 #ifdef COLORLS
66 #include <termcap.h>
67 #include <signal.h>
68 #endif
69 
70 #include "ls.h"
71 #include "extern.h"
72 
73 /*
74  * Upward approximation of the maximum number of characters needed to
75  * represent a value of integral type t as a string, excluding the
76  * NUL terminator, with provision for a sign.
77  */
78 #define	STRBUF_SIZEOF(t)	(1 + CHAR_BIT * sizeof(t) / 3 + 1)
79 
80 /*
81  * MAKENINES(n) turns n into (10**n)-1.  This is useful for converting a width
82  * into a number that wide in decimal.
83  * XXX: Overflows are not considered.
84  */
85 #define MAKENINES(n)							\
86 	do {								\
87 		intmax_t i;						\
88 									\
89 		/* Use a loop as all values of n are small. */		\
90 		for (i = 1; n > 0; i *= 10)				\
91 			n--;						\
92 		n = i - 1;						\
93 	} while(0)
94 
95 static void	 display(const FTSENT *, FTSENT *, int);
96 static int	 mastercmp(const FTSENT * const *, const FTSENT * const *);
97 static void	 traverse(int, char **, int);
98 
99 static void (*printfcn)(const DISPLAY *);
100 static int (*sortfcn)(const FTSENT *, const FTSENT *);
101 
102 long blocksize;			/* block size units */
103 int termwidth = 80;		/* default terminal width */
104 
105 /* flags */
106        int f_accesstime;	/* use time of last access */
107        int f_birthtime;		/* use time of birth */
108        int f_flags;		/* show flags associated with a file */
109        int f_humanval;		/* show human-readable file sizes */
110        int f_inode;		/* print inode */
111 static int f_kblocks;		/* print size in kilobytes */
112 static int f_listdir;		/* list actual directory, not contents */
113 static int f_listdot;		/* list files beginning with . */
114 static int f_noautodot;		/* do not automatically enable -A for root */
115        int f_longform;		/* long listing format */
116 static int f_nofollow;		/* don't follow symbolic link arguments */
117        int f_nonprint;		/* show unprintables as ? */
118 static int f_nosort;		/* don't sort output */
119        int f_notabs;		/* don't use tab-separated multi-col output */
120 static int f_numericonly;	/* don't convert uid/gid to name */
121        int f_octal;		/* show unprintables as \xxx */
122        int f_octal_escape;	/* like f_octal but use C escapes if possible */
123 static int f_recursive;		/* ls subdirectories also */
124 static int f_reversesort;	/* reverse whatever sort is used */
125        int f_sectime;		/* print the real time for all files */
126 static int f_singlecol;		/* use single column output */
127        int f_size;		/* list size in short listing */
128        int f_slash;		/* similar to f_type, but only for dirs */
129        int f_sortacross;	/* sort across rows, not down columns */
130        int f_statustime;	/* use time of last mode change */
131 static int f_stream;		/* stream the output, separate with commas */
132 static int f_timesort;		/* sort by time vice name */
133        char *f_timeformat;      /* user-specified time format */
134 static int f_sizesort;
135        int f_type;		/* add type character for non-regular files */
136 static int f_whiteout;		/* show whiteout entries */
137        int f_label;		/* show MAC label */
138 #ifdef COLORLS
139        int f_color;		/* add type in color for non-regular files */
140 
141 char *ansi_bgcol;		/* ANSI sequence to set background colour */
142 char *ansi_fgcol;		/* ANSI sequence to set foreground colour */
143 char *ansi_coloff;		/* ANSI sequence to reset colours */
144 char *attrs_off;		/* ANSI sequence to turn off attributes */
145 char *enter_bold;		/* ANSI sequence to set color to bold mode */
146 #endif
147 
148 static int rval;
149 
150 int
151 main(int argc, char *argv[])
152 {
153 	static char dot[] = ".", *dotav[] = {dot, NULL};
154 	struct winsize win;
155 	int ch, fts_options, notused;
156 	char *p;
157 #ifdef COLORLS
158 	char termcapbuf[1024];	/* termcap definition buffer */
159 	char tcapbuf[512];	/* capability buffer */
160 	char *bp = tcapbuf;
161 #endif
162 
163 	(void)setlocale(LC_ALL, "");
164 
165 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
166 	if (isatty(STDOUT_FILENO)) {
167 		termwidth = 80;
168 		if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
169 			termwidth = atoi(p);
170 		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1 &&
171 		    win.ws_col > 0)
172 			termwidth = win.ws_col;
173 		f_nonprint = 1;
174 	} else {
175 		f_singlecol = 1;
176 		/* retrieve environment variable, in case of explicit -C */
177 		p = getenv("COLUMNS");
178 		if (p)
179 			termwidth = atoi(p);
180 	}
181 
182 	fts_options = FTS_PHYSICAL;
183  	while ((ch = getopt(argc, argv,
184 	    "1ABCD:FGHILPRSTUWZabcdfghiklmnopqrstuwx")) != -1) {
185 		switch (ch) {
186 		/*
187 		 * The -1, -C, -x and -l options all override each other so
188 		 * shell aliasing works right.
189 		 */
190 		case '1':
191 			f_singlecol = 1;
192 			f_longform = 0;
193 			f_stream = 0;
194 			break;
195 		case 'B':
196 			f_nonprint = 0;
197 			f_octal = 1;
198 			f_octal_escape = 0;
199 			break;
200 		case 'C':
201 			f_sortacross = f_longform = f_singlecol = 0;
202 			break;
203                 case 'D':
204                         f_timeformat = optarg;
205                         break;
206 		case 'l':
207 			f_longform = 1;
208 			f_singlecol = 0;
209 			f_stream = 0;
210 			break;
211 		case 'x':
212 			f_sortacross = 1;
213 			f_longform = 0;
214 			f_singlecol = 0;
215 			break;
216 		/* The -c, -u, and -U options override each other. */
217 		case 'c':
218 			f_statustime = 1;
219 			f_accesstime = 0;
220 			f_birthtime = 0;
221 			break;
222 		case 'u':
223 			f_accesstime = 1;
224 			f_statustime = 0;
225 			f_birthtime = 0;
226 			break;
227 		case 'U':
228 			f_birthtime = 1;
229 			f_accesstime = 0;
230 			f_statustime = 0;
231 			break;
232 		case 'F':
233 			f_type = 1;
234 			f_slash = 0;
235 			break;
236 		case 'H':
237 			fts_options |= FTS_COMFOLLOW;
238 			f_nofollow = 0;
239 			break;
240 		case 'G':
241 			setenv("CLICOLOR", "", 1);
242 			break;
243 		case 'L':
244 			fts_options &= ~FTS_PHYSICAL;
245 			fts_options |= FTS_LOGICAL;
246 			f_nofollow = 0;
247 			break;
248 		case 'P':
249 			fts_options &= ~FTS_COMFOLLOW;
250 			fts_options &= ~FTS_LOGICAL;
251 			fts_options |= FTS_PHYSICAL;
252 			f_nofollow = 1;
253 			break;
254 		case 'R':
255 			f_recursive = 1;
256 			break;
257 		case 'a':
258 			fts_options |= FTS_SEEDOT;
259 			/* FALLTHROUGH */
260 		case 'A':
261 			f_listdot = 1;
262 			break;
263 		case 'I':
264 			f_noautodot = 1;
265 			break;
266 		/* The -d option turns off the -R option. */
267 		case 'd':
268 			f_listdir = 1;
269 			f_recursive = 0;
270 			break;
271 		case 'f':
272 			f_nosort = 1;
273 			break;
274 		case 'g':	/* Compatibility with 4.3BSD. */
275 			break;
276 		case 'h':
277 			f_humanval = 1;
278 			break;
279 		case 'i':
280 			f_inode = 1;
281 			break;
282 		case 'k':
283 			f_humanval = 0;
284 			f_kblocks = 1;
285 			break;
286 		case 'm':
287 			f_stream = 1;
288 			f_singlecol = 0;
289 			f_longform = 0;
290 			break;
291 		case 'n':
292 			f_numericonly = 1;
293 			break;
294 		case 'o':
295 			f_flags = 1;
296 			break;
297 		case 'p':
298 			f_slash = 1;
299 			f_type = 1;
300 			break;
301 		case 'q':
302 			f_nonprint = 1;
303 			f_octal = 0;
304 			f_octal_escape = 0;
305 			break;
306 		case 'r':
307 			f_reversesort = 1;
308 			break;
309 		case 's':
310 			f_size = 1;
311 			break;
312 		case 'T':
313 			f_sectime = 1;
314 			break;
315 		/* The -t and -S options override each other. */
316 		case 't':
317 			f_timesort = 1;
318 			f_sizesort = 0;
319 			break;
320 		case 'S':
321 			f_sizesort = 1;
322 			f_timesort = 0;
323 			break;
324 		case 'W':
325 			f_whiteout = 1;
326 			break;
327 		case 'b':
328 			f_nonprint = 0;
329 			f_octal = 0;
330 			f_octal_escape = 1;
331 			break;
332 		case 'w':
333 			f_nonprint = 0;
334 			f_octal = 0;
335 			f_octal_escape = 0;
336 			break;
337 		case 'Z':
338 			f_label = 1;
339 			break;
340 		default:
341 		case '?':
342 			usage();
343 		}
344 	}
345 	argc -= optind;
346 	argv += optind;
347 
348 	/* Root is -A automatically unless -I. */
349 	if (!f_listdot && getuid() == (uid_t)0 && !f_noautodot)
350 		f_listdot = 1;
351 
352 	/* Enabling of colours is conditional on the environment. */
353 	if (getenv("CLICOLOR") &&
354 	    (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
355 #ifdef COLORLS
356 		if (tgetent(termcapbuf, getenv("TERM")) == 1) {
357 			ansi_fgcol = tgetstr("AF", &bp);
358 			ansi_bgcol = tgetstr("AB", &bp);
359 			attrs_off = tgetstr("me", &bp);
360 			enter_bold = tgetstr("md", &bp);
361 
362 			/* To switch colours off use 'op' if
363 			 * available, otherwise use 'oc', or
364 			 * don't do colours at all. */
365 			ansi_coloff = tgetstr("op", &bp);
366 			if (!ansi_coloff)
367 				ansi_coloff = tgetstr("oc", &bp);
368 			if (ansi_fgcol && ansi_bgcol && ansi_coloff)
369 				f_color = 1;
370 		}
371 #else
372 		warnx("color support not compiled in");
373 #endif /*COLORLS*/
374 
375 #ifdef COLORLS
376 	if (f_color) {
377 		/*
378 		 * We can't put tabs and color sequences together:
379 		 * column number will be incremented incorrectly
380 		 * for "stty oxtabs" mode.
381 		 */
382 		f_notabs = 1;
383 		(void)signal(SIGINT, colorquit);
384 		(void)signal(SIGQUIT, colorquit);
385 		parsecolors(getenv("LSCOLORS"));
386 	}
387 #endif
388 
389 	/*
390 	 * If not -F, -i, -l, -s, -S or -t options, don't require stat
391 	 * information, unless in color mode in which case we do
392 	 * need this to determine which colors to display.
393 	 */
394 	if (!f_inode && !f_longform && !f_size && !f_timesort &&
395 	    !f_sizesort && !f_type
396 #ifdef COLORLS
397 	    && !f_color
398 #endif
399 	    )
400 		fts_options |= FTS_NOSTAT;
401 
402 	/*
403 	 * If not -F, -P, -d or -l options, follow any symbolic links listed on
404 	 * the command line.
405 	 */
406 	if (!f_nofollow && !f_longform && !f_listdir && (!f_type || f_slash))
407 		fts_options |= FTS_COMFOLLOW;
408 
409 	/*
410 	 * If -W, show whiteout entries
411 	 */
412 #ifdef FTS_WHITEOUT
413 	if (f_whiteout)
414 		fts_options |= FTS_WHITEOUT;
415 #endif
416 
417 	/* If -i, -l or -s, figure out block size. */
418 	if (f_inode || f_longform || f_size) {
419 		if (f_kblocks)
420 			blocksize = 2;
421 		else {
422 			(void)getbsize(&notused, &blocksize);
423 			blocksize /= 512;
424 		}
425 	}
426 	/* Select a sort function. */
427 	if (f_reversesort) {
428 		if (!f_timesort && !f_sizesort)
429 			sortfcn = revnamecmp;
430 		else if (f_sizesort)
431 			sortfcn = revsizecmp;
432 		else if (f_accesstime)
433 			sortfcn = revacccmp;
434 		else if (f_birthtime)
435 			sortfcn = revbirthcmp;
436 		else if (f_statustime)
437 			sortfcn = revstatcmp;
438 		else		/* Use modification time. */
439 			sortfcn = revmodcmp;
440 	} else {
441 		if (!f_timesort && !f_sizesort)
442 			sortfcn = namecmp;
443 		else if (f_sizesort)
444 			sortfcn = sizecmp;
445 		else if (f_accesstime)
446 			sortfcn = acccmp;
447 		else if (f_birthtime)
448 			sortfcn = birthcmp;
449 		else if (f_statustime)
450 			sortfcn = statcmp;
451 		else		/* Use modification time. */
452 			sortfcn = modcmp;
453 	}
454 
455 	/* Select a print function. */
456 	if (f_singlecol)
457 		printfcn = printscol;
458 	else if (f_longform)
459 		printfcn = printlong;
460 	else if (f_stream)
461 		printfcn = printstream;
462 	else
463 		printfcn = printcol;
464 
465 	if (argc)
466 		traverse(argc, argv, fts_options);
467 	else
468 		traverse(1, dotav, fts_options);
469 	exit(rval);
470 }
471 
472 static int output;		/* If anything output. */
473 
474 /*
475  * Traverse() walks the logical directory structure specified by the argv list
476  * in the order specified by the mastercmp() comparison function.  During the
477  * traversal it passes linked lists of structures to display() which represent
478  * a superset (may be exact set) of the files to be displayed.
479  */
480 static void
481 traverse(int argc, char *argv[], int options)
482 {
483 	FTS *ftsp;
484 	FTSENT *p, *chp;
485 	int ch_options;
486 
487 	if ((ftsp =
488 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
489 		err(1, "fts_open");
490 
491 	/*
492 	 * We ignore errors from fts_children here since they will be
493 	 * replicated and signalled on the next call to fts_read() below.
494 	 */
495 	chp = fts_children(ftsp, 0);
496 	if (chp != NULL)
497 		display(NULL, chp, options);
498 	if (f_listdir)
499 		return;
500 
501 	/*
502 	 * If not recursing down this tree and don't need stat info, just get
503 	 * the names.
504 	 */
505 	ch_options = !f_recursive && !f_label &&
506 	    options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
507 
508 	while ((p = fts_read(ftsp)) != NULL)
509 		switch (p->fts_info) {
510 		case FTS_DC:
511 			warnx("%s: directory causes a cycle", p->fts_name);
512 			break;
513 		case FTS_DNR:
514 		case FTS_ERR:
515 			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
516 			rval = 1;
517 			break;
518 		case FTS_D:
519 			if (p->fts_level != FTS_ROOTLEVEL &&
520 			    p->fts_name[0] == '.' && !f_listdot)
521 				break;
522 
523 			/*
524 			 * If already output something, put out a newline as
525 			 * a separator.  If multiple arguments, precede each
526 			 * directory with its name.
527 			 */
528 			if (output) {
529 				putchar('\n');
530 				(void)printname(p->fts_path);
531 				puts(":");
532 			} else if (argc > 1) {
533 				(void)printname(p->fts_path);
534 				puts(":");
535 				output = 1;
536 			}
537 			chp = fts_children(ftsp, ch_options);
538 			display(p, chp, options);
539 
540 			if (!f_recursive && chp != NULL)
541 				(void)fts_set(ftsp, p, FTS_SKIP);
542 			break;
543 		default:
544 			break;
545 		}
546 	if (errno)
547 		err(1, "fts_read");
548 }
549 
550 /*
551  * Display() takes a linked list of FTSENT structures and passes the list
552  * along with any other necessary information to the print function.  P
553  * points to the parent directory of the display list.
554  */
555 static void
556 display(const FTSENT *p, FTSENT *list, int options)
557 {
558 	struct stat *sp;
559 	DISPLAY d;
560 	FTSENT *cur;
561 	NAMES *np;
562 	off_t maxsize;
563 	long maxblock;
564 	uintmax_t maxinode;
565 	u_long btotal, labelstrlen, maxlen, maxnlink;
566 	u_long maxlabelstr;
567 	u_int sizelen;
568 	int maxflags;
569 	gid_t maxgroup;
570 	uid_t maxuser;
571 	size_t flen, ulen, glen;
572 	char *initmax;
573 	int entries, needstats;
574 	const char *user, *group;
575 	char *flags, *labelstr = NULL;
576 	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
577 	char nuser[STRBUF_SIZEOF(gid_t) + 1];
578 
579 	needstats = f_inode || f_longform || f_size;
580 	flen = 0;
581 	btotal = 0;
582 	initmax = getenv("LS_COLWIDTHS");
583 	/* Fields match -lios order.  New ones should be added at the end. */
584 	maxlabelstr = maxblock = maxlen = maxnlink = 0;
585 	maxuser = maxgroup = maxflags = maxsize = 0;
586 	maxinode = 0;
587 	if (initmax != NULL && *initmax != '\0') {
588 		char *initmax2, *jinitmax;
589 		int ninitmax;
590 
591 		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
592 		jinitmax = malloc(strlen(initmax) * 2 + 2);
593 		if (jinitmax == NULL)
594 			err(1, "malloc");
595 		initmax2 = jinitmax;
596 		if (*initmax == ':')
597 			strcpy(initmax2, "0:"), initmax2 += 2;
598 		else
599 			*initmax2++ = *initmax, *initmax2 = '\0';
600 		for (initmax++; *initmax != '\0'; initmax++) {
601 			if (initmax[-1] == ':' && initmax[0] == ':') {
602 				*initmax2++ = '0';
603 				*initmax2++ = initmax[0];
604 				initmax2[1] = '\0';
605 			} else {
606 				*initmax2++ = initmax[0];
607 				initmax2[1] = '\0';
608 			}
609 		}
610 		if (initmax2[-1] == ':')
611 			strcpy(initmax2, "0");
612 
613 		ninitmax = sscanf(jinitmax,
614 		    " %ju : %ld : %lu : %u : %u : %i : %jd : %lu : %lu ",
615 		    &maxinode, &maxblock, &maxnlink, &maxuser,
616 		    &maxgroup, &maxflags, &maxsize, &maxlen, &maxlabelstr);
617 		f_notabs = 1;
618 		switch (ninitmax) {
619 		case 0:
620 			maxinode = 0;
621 			/* FALLTHROUGH */
622 		case 1:
623 			maxblock = 0;
624 			/* FALLTHROUGH */
625 		case 2:
626 			maxnlink = 0;
627 			/* FALLTHROUGH */
628 		case 3:
629 			maxuser = 0;
630 			/* FALLTHROUGH */
631 		case 4:
632 			maxgroup = 0;
633 			/* FALLTHROUGH */
634 		case 5:
635 			maxflags = 0;
636 			/* FALLTHROUGH */
637 		case 6:
638 			maxsize = 0;
639 			/* FALLTHROUGH */
640 		case 7:
641 			maxlen = 0;
642 			/* FALLTHROUGH */
643 		case 8:
644 			maxlabelstr = 0;
645 			/* FALLTHROUGH */
646 #ifdef COLORLS
647 			if (!f_color)
648 #endif
649 				f_notabs = 0;
650 			/* FALLTHROUGH */
651 		default:
652 			break;
653 		}
654 		MAKENINES(maxinode);
655 		MAKENINES(maxblock);
656 		MAKENINES(maxnlink);
657 		MAKENINES(maxsize);
658 		free(jinitmax);
659 	}
660 	d.s_size = 0;
661 	sizelen = 0;
662 	flags = NULL;
663 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
664 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
665 			warnx("%s: %s",
666 			    cur->fts_name, strerror(cur->fts_errno));
667 			cur->fts_number = NO_PRINT;
668 			rval = 1;
669 			continue;
670 		}
671 		/*
672 		 * P is NULL if list is the argv list, to which different rules
673 		 * apply.
674 		 */
675 		if (p == NULL) {
676 			/* Directories will be displayed later. */
677 			if (cur->fts_info == FTS_D && !f_listdir) {
678 				cur->fts_number = NO_PRINT;
679 				continue;
680 			}
681 		} else {
682 			/* Only display dot file if -a/-A set. */
683 			if (cur->fts_name[0] == '.' && !f_listdot) {
684 				cur->fts_number = NO_PRINT;
685 				continue;
686 			}
687 		}
688 		if (cur->fts_namelen > maxlen)
689 			maxlen = cur->fts_namelen;
690 		if (f_octal || f_octal_escape) {
691 			u_long t = len_octal(cur->fts_name, cur->fts_namelen);
692 
693 			if (t > maxlen)
694 				maxlen = t;
695 		}
696 		if (needstats) {
697 			sp = cur->fts_statp;
698 			if (sp->st_blocks > maxblock)
699 				maxblock = sp->st_blocks;
700 			if (sp->st_ino > maxinode)
701 				maxinode = sp->st_ino;
702 			if (sp->st_nlink > maxnlink)
703 				maxnlink = sp->st_nlink;
704 			if (sp->st_size > maxsize)
705 				maxsize = sp->st_size;
706 
707 			btotal += sp->st_blocks;
708 			if (f_longform) {
709 				if (f_numericonly) {
710 					(void)snprintf(nuser, sizeof(nuser),
711 					    "%u", sp->st_uid);
712 					(void)snprintf(ngroup, sizeof(ngroup),
713 					    "%u", sp->st_gid);
714 					user = nuser;
715 					group = ngroup;
716 				} else {
717 					user = user_from_uid(sp->st_uid, 0);
718 					group = group_from_gid(sp->st_gid, 0);
719 				}
720 				if ((ulen = strlen(user)) > maxuser)
721 					maxuser = ulen;
722 				if ((glen = strlen(group)) > maxgroup)
723 					maxgroup = glen;
724 				if (f_flags) {
725 					flags = fflagstostr(sp->st_flags);
726 					if (flags != NULL && *flags == '\0') {
727 						free(flags);
728 						flags = strdup("-");
729 					}
730 					if (flags == NULL)
731 						err(1, "fflagstostr");
732 					flen = strlen(flags);
733 					if (flen > (size_t)maxflags)
734 						maxflags = flen;
735 				} else
736 					flen = 0;
737 				labelstr = NULL;
738 				if (f_label) {
739 					char name[PATH_MAX + 1];
740 					mac_t label;
741 					int error;
742 
743 					error = mac_prepare_file_label(&label);
744 					if (error == -1) {
745 						warn("MAC label for %s/%s",
746 						    cur->fts_parent->fts_path,
747 						    cur->fts_name);
748 						goto label_out;
749 					}
750 
751 					if (cur->fts_level == FTS_ROOTLEVEL)
752 						snprintf(name, sizeof(name),
753 						    "%s", cur->fts_name);
754 					else
755 						snprintf(name, sizeof(name),
756 						    "%s/%s", cur->fts_parent->
757 						    fts_accpath, cur->fts_name);
758 
759 					if (options & FTS_LOGICAL)
760 						error = mac_get_file(name,
761 						    label);
762 					else
763 						error = mac_get_link(name,
764 						    label);
765 					if (error == -1) {
766 						warn("MAC label for %s/%s",
767 						    cur->fts_parent->fts_path,
768 						    cur->fts_name);
769 						mac_free(label);
770 						goto label_out;
771 					}
772 
773 					error = mac_to_text(label,
774 					    &labelstr);
775 					if (error == -1) {
776 						warn("MAC label for %s/%s",
777 						    cur->fts_parent->fts_path,
778 						    cur->fts_name);
779 						mac_free(label);
780 						goto label_out;
781 					}
782 					mac_free(label);
783 label_out:
784 					if (labelstr == NULL)
785 						labelstr = strdup("-");
786 					labelstrlen = strlen(labelstr);
787 					if (labelstrlen > maxlabelstr)
788 						maxlabelstr = labelstrlen;
789 				} else
790 					labelstrlen = 0;
791 
792 				if ((np = malloc(sizeof(NAMES) + labelstrlen +
793 				    ulen + glen + flen + 4)) == NULL)
794 					err(1, "malloc");
795 
796 				np->user = &np->data[0];
797 				(void)strcpy(np->user, user);
798 				np->group = &np->data[ulen + 1];
799 				(void)strcpy(np->group, group);
800 
801 				if (S_ISCHR(sp->st_mode) ||
802 				    S_ISBLK(sp->st_mode)) {
803 					sizelen = snprintf(NULL, 0,
804 					    "%#jx", (uintmax_t)sp->st_rdev);
805 					if (d.s_size < sizelen)
806 						d.s_size = sizelen;
807 				}
808 
809 				if (f_flags) {
810 					np->flags = &np->data[ulen + glen + 2];
811 					(void)strcpy(np->flags, flags);
812 					free(flags);
813 				}
814 				if (f_label) {
815 					np->label = &np->data[ulen + glen + 2
816 					    + (f_flags ? flen + 1 : 0)];
817 					(void)strcpy(np->label, labelstr);
818 					free(labelstr);
819 				}
820 				cur->fts_pointer = np;
821 			}
822 		}
823 		++entries;
824 	}
825 
826 	/*
827 	 * If there are no entries to display, we normally stop right
828 	 * here.  However, we must continue if we have to display the
829 	 * total block count.  In this case, we display the total only
830 	 * on the second (p != NULL) pass.
831 	 */
832 	if (!entries && (!(f_longform || f_size) || p == NULL))
833 		return;
834 
835 	d.list = list;
836 	d.entries = entries;
837 	d.maxlen = maxlen;
838 	if (needstats) {
839 		d.btotal = btotal;
840 		d.s_block = snprintf(NULL, 0, "%lu", howmany(maxblock, blocksize));
841 		d.s_flags = maxflags;
842 		d.s_label = maxlabelstr;
843 		d.s_group = maxgroup;
844 		d.s_inode = snprintf(NULL, 0, "%ju", maxinode);
845 		d.s_nlink = snprintf(NULL, 0, "%lu", maxnlink);
846 		sizelen = f_humanval ? HUMANVALSTR_LEN :
847 		    snprintf(NULL, 0, "%ju", maxsize);
848 		if (d.s_size < sizelen)
849 			d.s_size = sizelen;
850 		d.s_user = maxuser;
851 	}
852 	printfcn(&d);
853 	output = 1;
854 
855 	if (f_longform)
856 		for (cur = list; cur; cur = cur->fts_link)
857 			free(cur->fts_pointer);
858 }
859 
860 /*
861  * Ordering for mastercmp:
862  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
863  * as larger than directories.  Within either group, use the sort function.
864  * All other levels use the sort function.  Error entries remain unsorted.
865  */
866 static int
867 mastercmp(const FTSENT * const *a, const FTSENT * const *b)
868 {
869 	int a_info, b_info;
870 
871 	a_info = (*a)->fts_info;
872 	if (a_info == FTS_ERR)
873 		return (0);
874 	b_info = (*b)->fts_info;
875 	if (b_info == FTS_ERR)
876 		return (0);
877 
878 	if (a_info == FTS_NS || b_info == FTS_NS)
879 		return (namecmp(*a, *b));
880 
881 	if (a_info != b_info &&
882 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
883 		if (a_info == FTS_D)
884 			return (1);
885 		if (b_info == FTS_D)
886 			return (-1);
887 	}
888 	return (sortfcn(*a, *b));
889 }
890