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