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