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