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