xref: /freebsd/bin/ls/ls.c (revision c11e094d96120a2e0e726ed9705ae0ec08db49b6)
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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 
39 __FBSDID("$FreeBSD$");
40 
41 #ifndef lint
42 static const char copyright[] =
43 "@(#) Copyright (c) 1989, 1993, 1994\n\
44 	The Regents of the University of California.  All rights reserved.\n";
45 #endif /* not lint */
46 
47 #if 0
48 #ifndef lint
49 static char sccsid[] = "@(#)ls.c	8.5 (Berkeley) 4/2/94";
50 #endif /* not lint */
51 #endif
52 
53 #include <sys/types.h>
54 #include <sys/stat.h>
55 #include <sys/ioctl.h>
56 
57 #include <dirent.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fts.h>
61 #include <grp.h>
62 #include <limits.h>
63 #include <locale.h>
64 #include <pwd.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69 #ifdef COLORLS
70 #include <termcap.h>
71 #include <signal.h>
72 #endif
73 
74 #include "ls.h"
75 #include "extern.h"
76 #include "lomac.h"
77 
78 /*
79  * Upward approximation of the maximum number of characters needed to
80  * represent a value of integral type t as a string, excluding the
81  * NUL terminator, with provision for a sign.
82  */
83 #define	STRBUF_SIZEOF(t)	(1 + CHAR_BIT * sizeof(t) / 3 + 1)
84 
85 static void	 display(FTSENT *, FTSENT *);
86 static u_quad_t	 makenines(u_long);
87 static int	 mastercmp(const FTSENT **, const FTSENT **);
88 static void	 traverse(int, char **, int);
89 
90 static void (*printfcn)(DISPLAY *);
91 static int (*sortfcn)(const FTSENT *, const FTSENT *);
92 
93 long blocksize;			/* block size units */
94 int termwidth = 80;		/* default terminal width */
95 
96 /* flags */
97        int f_accesstime;	/* use time of last access */
98        int f_flags;		/* show flags 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        int f_stream;		/* stream the output, seperate 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        int f_lomac;		/* show LOMAC attributes */
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 	(void)setlocale(LC_ALL, "");
150 
151 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
152 	if (isatty(STDOUT_FILENO)) {
153 		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
154 		    !win.ws_col) {
155 			if ((p = getenv("COLUMNS")) != NULL)
156 				termwidth = atoi(p);
157 		} else
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, "1ABCFGHLPRTWZabcdfghiklmnopqrstuwx"))
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 		/* The -c and -u options override each other. */
204 		case 'c':
205 			f_statustime = 1;
206 			f_accesstime = 0;
207 			break;
208 		case 'u':
209 			f_accesstime = 1;
210 			f_statustime = 0;
211 			break;
212 		case 'F':
213 			f_type = 1;
214 			f_slash = 0;
215 			break;
216 		case 'H':
217 			fts_options |= FTS_COMFOLLOW;
218 			break;
219 		case 'G':
220 			setenv("CLICOLOR", "", 1);
221 			break;
222 		case 'L':
223 			fts_options &= ~FTS_PHYSICAL;
224 			fts_options |= FTS_LOGICAL;
225 			break;
226 		case 'P':
227 			fts_options &= ~FTS_COMFOLLOW;
228 			fts_options &= ~FTS_LOGICAL;
229 			fts_options |= FTS_PHYSICAL;
230 			break;
231 		case 'R':
232 			f_recursive = 1;
233 			break;
234 		case 'a':
235 			fts_options |= FTS_SEEDOT;
236 			/* FALLTHROUGH */
237 		case 'A':
238 			f_listdot = 1;
239 			break;
240 		/* The -d option turns off the -R option. */
241 		case 'd':
242 			f_listdir = 1;
243 			f_recursive = 0;
244 			break;
245 		case 'f':
246 			f_nosort = 1;
247 			break;
248 		case 'g':	/* Compatibility with 4.3BSD. */
249 			break;
250 		case 'h':
251 			f_humanval = 1;
252 			break;
253 		case 'i':
254 			f_inode = 1;
255 			break;
256 		case 'k':
257 			f_kblocks = 1;
258 			break;
259 		case 'm':
260 			f_stream = 1;
261 			f_singlecol = 0;
262 			f_longform = 0;
263 			break;
264 		case 'n':
265 			f_numericonly = 1;
266 			break;
267 		case 'o':
268 			f_flags = 1;
269 			break;
270 		case 'p':
271 			f_slash = 1;
272 			f_type = 1;
273 			break;
274 		case 'q':
275 			f_nonprint = 1;
276 			f_octal = 0;
277 			f_octal_escape = 0;
278 			break;
279 		case 'r':
280 			f_reversesort = 1;
281 			break;
282 		case 's':
283 			f_size = 1;
284 			break;
285 		case 'T':
286 			f_sectime = 1;
287 			break;
288 		case 't':
289 			f_timesort = 1;
290 			break;
291 		case 'W':
292 			f_whiteout = 1;
293 			break;
294 		case 'b':
295 			f_nonprint = 0;
296 			f_octal = 0;
297 			f_octal_escape = 1;
298 			break;
299 		case 'w':
300 			f_nonprint = 0;
301 			f_octal = 0;
302 			f_octal_escape = 0;
303 			break;
304 		case 'Z':
305 			f_lomac = 1;
306 			break;
307 		default:
308 		case '?':
309 			usage();
310 		}
311 	}
312 	argc -= optind;
313 	argv += optind;
314 
315 	/* Enabling of colours is conditional on the environment. */
316 	if (getenv("CLICOLOR") &&
317 	    (isatty(STDOUT_FILENO) || getenv("CLICOLOR_FORCE")))
318 #ifdef COLORLS
319 		if (tgetent(termcapbuf, getenv("TERM")) == 1) {
320 			ansi_fgcol = tgetstr("AF", &bp);
321 			ansi_bgcol = tgetstr("AB", &bp);
322 			attrs_off = tgetstr("me", &bp);
323 			enter_bold = tgetstr("md", &bp);
324 
325 			/* To switch colours off use 'op' if
326 			 * available, otherwise use 'oc', or
327 			 * don't do colours at all. */
328 			ansi_coloff = tgetstr("op", &bp);
329 			if (!ansi_coloff)
330 				ansi_coloff = tgetstr("oc", &bp);
331 			if (ansi_fgcol && ansi_bgcol && ansi_coloff)
332 				f_color = 1;
333 		}
334 #else
335 		(void)fprintf(stderr, "Color support not compiled in.\n");
336 #endif /*COLORLS*/
337 
338 #ifdef COLORLS
339 	if (f_color) {
340 		/*
341 		 * We can't put tabs and color sequences together:
342 		 * column number will be incremented incorrectly
343 		 * for "stty oxtabs" mode.
344 		 */
345 		f_notabs = 1;
346 		(void)signal(SIGINT, colorquit);
347 		(void)signal(SIGQUIT, colorquit);
348 		parsecolors(getenv("LSCOLORS"));
349 	}
350 #endif
351 
352 	/*
353 	 * If not -F, -i, -l, -s or -t options, don't require stat
354 	 * information, unless in color mode in which case we do
355 	 * need this to determine which colors to display.
356 	 */
357 	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type
358 #ifdef COLORLS
359 	    && !f_color
360 #endif
361 	    )
362 		fts_options |= FTS_NOSTAT;
363 
364 	/*
365 	 * If not -F, -d or -l options, follow any symbolic links listed on
366 	 * the command line.
367 	 */
368 	if (!f_longform && !f_listdir && !f_type)
369 		fts_options |= FTS_COMFOLLOW;
370 
371 	/*
372 	 * If -W, show whiteout entries
373 	 */
374 #ifdef FTS_WHITEOUT
375 	if (f_whiteout)
376 		fts_options |= FTS_WHITEOUT;
377 #endif
378 
379 	/* If -l or -s, figure out block size. */
380 	if (f_longform || f_size) {
381 		if (f_kblocks)
382 			blocksize = 2;
383 		else {
384 			(void)getbsize(&notused, &blocksize);
385 			blocksize /= 512;
386 		}
387 	}
388 	/* Select a sort function. */
389 	if (f_reversesort) {
390 		if (!f_timesort)
391 			sortfcn = revnamecmp;
392 		else if (f_accesstime)
393 			sortfcn = revacccmp;
394 		else if (f_statustime)
395 			sortfcn = revstatcmp;
396 		else		/* Use modification time. */
397 			sortfcn = revmodcmp;
398 	} else {
399 		if (!f_timesort)
400 			sortfcn = namecmp;
401 		else if (f_accesstime)
402 			sortfcn = acccmp;
403 		else if (f_statustime)
404 			sortfcn = statcmp;
405 		else		/* Use modification time. */
406 			sortfcn = modcmp;
407 	}
408 
409 	/* Select a print function. */
410 	if (f_singlecol)
411 		printfcn = printscol;
412 	else if (f_longform)
413 		printfcn = printlong;
414 	else if (f_stream)
415 		printfcn = printstream;
416 	else
417 		printfcn = printcol;
418 
419 	if (argc)
420 		traverse(argc, argv, fts_options);
421 	else
422 		traverse(1, dotav, fts_options);
423 	exit(rval);
424 }
425 
426 static int output;		/* If anything output. */
427 
428 /*
429  * Traverse() walks the logical directory structure specified by the argv list
430  * in the order specified by the mastercmp() comparison function.  During the
431  * traversal it passes linked lists of structures to display() which represent
432  * a superset (may be exact set) of the files to be displayed.
433  */
434 static void
435 traverse(int argc, char *argv[], int options)
436 {
437 	FTS *ftsp;
438 	FTSENT *p, *chp;
439 	int ch_options;
440 
441 	if ((ftsp =
442 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
443 		err(1, NULL);
444 
445 	display(NULL, fts_children(ftsp, 0));
446 	if (f_listdir)
447 		return;
448 
449 	/*
450 	 * If not recursing down this tree and don't need stat info, just get
451 	 * the names.
452 	 */
453 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
454 
455 	while ((p = fts_read(ftsp)) != NULL)
456 		switch (p->fts_info) {
457 		case FTS_DC:
458 			warnx("%s: directory causes a cycle", p->fts_name);
459 			break;
460 		case FTS_DNR:
461 		case FTS_ERR:
462 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
463 			rval = 1;
464 			break;
465 		case FTS_D:
466 			if (p->fts_level != FTS_ROOTLEVEL &&
467 			    p->fts_name[0] == '.' && !f_listdot)
468 				break;
469 
470 			/*
471 			 * If already output something, put out a newline as
472 			 * a separator.  If multiple arguments, precede each
473 			 * directory with its name.
474 			 */
475 			if (output)
476 				(void)printf("\n%s:\n", p->fts_path);
477 			else if (argc > 1) {
478 				(void)printf("%s:\n", p->fts_path);
479 				output = 1;
480 			}
481 			chp = fts_children(ftsp, ch_options);
482 			display(p, chp);
483 
484 			if (!f_recursive && chp != NULL)
485 				(void)fts_set(ftsp, p, FTS_SKIP);
486 			break;
487 		default:
488 			break;
489 		}
490 	if (errno)
491 		err(1, "fts_read");
492 }
493 
494 /*
495  * Display() takes a linked list of FTSENT structures and passes the list
496  * along with any other necessary information to the print function.  P
497  * points to the parent directory of the display list.
498  */
499 static void
500 display(FTSENT *p, FTSENT *list)
501 {
502 	struct stat *sp;
503 	DISPLAY d;
504 	FTSENT *cur;
505 	NAMES *np;
506 	off_t maxsize;
507 	u_long btotal, lattrlen, maxblock, maxinode, maxlen, maxnlink, maxlattr;
508 	int bcfile, maxflags;
509 	gid_t maxgroup;
510 	uid_t maxuser;
511 	size_t flen, ulen, glen;
512 	char *initmax;
513 	int entries, needstats;
514 	const char *user, *group;
515 	char *flags, *lattr = NULL;
516 	char buf[STRBUF_SIZEOF(u_quad_t) + 1];
517 	char ngroup[STRBUF_SIZEOF(uid_t) + 1];
518 	char nuser[STRBUF_SIZEOF(gid_t) + 1];
519 
520 	/*
521 	 * If list is NULL there are two possibilities: that the parent
522 	 * directory p has no children, or that fts_children() returned an
523 	 * error.  We ignore the error case since it will be replicated
524 	 * on the next call to fts_read() on the post-order visit to the
525 	 * directory p, and will be signaled in traverse().
526 	 */
527 	if (list == NULL)
528 		return;
529 
530 	needstats = f_inode || f_longform || f_size;
531 	flen = 0;
532 	btotal = 0;
533 	initmax = getenv("LS_COLWIDTHS");
534 	/* Fields match -lios order.  New ones should be added at the end. */
535 	maxlattr = maxblock = maxinode = maxlen = maxnlink =
536 	    maxuser = maxgroup = maxflags = maxsize = 0;
537 	if (initmax != NULL && *initmax != '\0') {
538 		char *initmax2, *jinitmax;
539 		int ninitmax;
540 
541 		/* Fill-in "::" as "0:0:0" for the sake of scanf. */
542 		jinitmax = initmax2 = malloc(strlen(initmax) * 2 + 2);
543 		if (jinitmax == NULL)
544 			err(1, NULL);
545 		if (*initmax == ':')
546 			strcpy(initmax2, "0:"), initmax2 += 2;
547 		else
548 			*initmax2++ = *initmax, *initmax2 = '\0';
549 		for (initmax++; *initmax != '\0'; initmax++) {
550 			if (initmax[-1] == ':' && initmax[0] == ':') {
551 				*initmax2++ = '0';
552 				*initmax2++ = initmax[0];
553 				initmax2[1] = '\0';
554 			} else {
555 				*initmax2++ = initmax[0];
556 				initmax2[1] = '\0';
557 			}
558 		}
559 		if (initmax2[-1] == ':')
560 			strcpy(initmax2, "0");
561 
562 		ninitmax = sscanf(jinitmax,
563 		    " %lu : %lu : %lu : %i : %i : %i : %llu : %lu : %lu ",
564 		    &maxinode, &maxblock, &maxnlink, &maxuser,
565 		    &maxgroup, &maxflags, &maxsize, &maxlen, &maxlattr);
566 		f_notabs = 1;
567 		switch (ninitmax) {
568 		case 0:
569 			maxinode = 0;
570 			/* fall through */
571 		case 1:
572 			maxblock = 0;
573 			/* fall through */
574 		case 2:
575 			maxnlink = 0;
576 			/* fall through */
577 		case 3:
578 			maxuser = 0;
579 			/* fall through */
580 		case 4:
581 			maxgroup = 0;
582 			/* fall through */
583 		case 5:
584 			maxflags = 0;
585 			/* fall through */
586 		case 6:
587 			maxsize = 0;
588 			/* fall through */
589 		case 7:
590 			maxlen = 0;
591 			/* fall through */
592 		case 8:
593 			maxlattr = 0;
594 			/* fall through */
595 #ifdef COLORLS
596 			if (!f_color)
597 #endif
598 				f_notabs = 0;
599 			/* fall through */
600 		default:
601 			break;
602 		}
603 		maxinode = makenines(maxinode);
604 		maxblock = makenines(maxblock);
605 		maxnlink = makenines(maxnlink);
606 		maxsize = makenines(maxsize);
607 	}
608 	if (f_lomac)
609 		lomac_start();
610 	bcfile = 0;
611 	flags = NULL;
612 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
613 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
614 			warnx("%s: %s",
615 			    cur->fts_name, strerror(cur->fts_errno));
616 			cur->fts_number = NO_PRINT;
617 			rval = 1;
618 			continue;
619 		}
620 		/*
621 		 * P is NULL if list is the argv list, to which different rules
622 		 * apply.
623 		 */
624 		if (p == NULL) {
625 			/* Directories will be displayed later. */
626 			if (cur->fts_info == FTS_D && !f_listdir) {
627 				cur->fts_number = NO_PRINT;
628 				continue;
629 			}
630 		} else {
631 			/* Only display dot file if -a/-A set. */
632 			if (cur->fts_name[0] == '.' && !f_listdot) {
633 				cur->fts_number = NO_PRINT;
634 				continue;
635 			}
636 		}
637 		if (cur->fts_namelen > maxlen)
638 			maxlen = cur->fts_namelen;
639 		if (f_octal || f_octal_escape) {
640 			u_long t = len_octal(cur->fts_name, cur->fts_namelen);
641 
642 			if (t > maxlen)
643 				maxlen = t;
644 		}
645 		if (needstats) {
646 			sp = cur->fts_statp;
647 			if (sp->st_blocks > maxblock)
648 				maxblock = sp->st_blocks;
649 			if (sp->st_ino > maxinode)
650 				maxinode = sp->st_ino;
651 			if (sp->st_nlink > maxnlink)
652 				maxnlink = sp->st_nlink;
653 			if (sp->st_size > maxsize)
654 				maxsize = sp->st_size;
655 
656 			btotal += sp->st_blocks;
657 			if (f_longform) {
658 				if (f_numericonly) {
659 					(void)snprintf(nuser, sizeof(nuser),
660 					    "%u", sp->st_uid);
661 					(void)snprintf(ngroup, sizeof(ngroup),
662 					    "%u", sp->st_gid);
663 					user = nuser;
664 					group = ngroup;
665 				} else {
666 					user = user_from_uid(sp->st_uid, 0);
667 					group = group_from_gid(sp->st_gid, 0);
668 				}
669 				if ((ulen = strlen(user)) > maxuser)
670 					maxuser = ulen;
671 				if ((glen = strlen(group)) > maxgroup)
672 					maxgroup = glen;
673 				if (f_flags) {
674 					flags = fflagstostr(sp->st_flags);
675 					if (flags != NULL && *flags == '\0') {
676 						free(flags);
677 						flags = strdup("-");
678 					}
679 					if (flags == NULL)
680 						err(1, NULL);
681 					flen = strlen(flags);
682 					if (flen > (size_t)maxflags)
683 						maxflags = flen;
684 				} else
685 					flen = 0;
686 				lattr = NULL;
687 				if (f_lomac) {
688 					lattr = get_lattr(cur);
689 					lattrlen = strlen(lattr);
690 					if (lattrlen > maxlattr)
691 						maxlattr = lattrlen;
692 				} else
693 					lattrlen = 0;
694 
695 				if ((np = malloc(sizeof(NAMES) + lattrlen +
696 				    ulen + glen + flen + 4)) == NULL)
697 					err(1, NULL);
698 
699 				np->user = &np->data[0];
700 				(void)strcpy(np->user, user);
701 				np->group = &np->data[ulen + 1];
702 				(void)strcpy(np->group, group);
703 
704 				if (S_ISCHR(sp->st_mode) ||
705 				    S_ISBLK(sp->st_mode))
706 					bcfile = 1;
707 
708 				if (f_flags) {
709 					np->flags = &np->data[ulen + glen + 2];
710 					(void)strcpy(np->flags, flags);
711 					free(flags);
712 				}
713 				if (f_lomac) {
714 					np->lattr = &np->data[ulen + glen + 2
715 					    + (f_flags ? flen + 1 : 0)];
716 					(void)strcpy(np->lattr, lattr);
717 					free(lattr);
718 				}
719 				cur->fts_pointer = np;
720 			}
721 		}
722 		++entries;
723 	}
724 
725 	if (!entries)
726 		return;
727 
728 	d.list = list;
729 	d.entries = entries;
730 	d.maxlen = maxlen;
731 	if (needstats) {
732 		d.bcfile = bcfile;
733 		d.btotal = btotal;
734 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
735 		d.s_block = strlen(buf);
736 		d.s_flags = maxflags;
737 		d.s_lattr = maxlattr;
738 		d.s_group = maxgroup;
739 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
740 		d.s_inode = strlen(buf);
741 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
742 		d.s_nlink = strlen(buf);
743 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
744 		d.s_size = strlen(buf);
745 		d.s_user = maxuser;
746 	}
747 	printfcn(&d);
748 	output = 1;
749 
750 	if (f_longform)
751 		for (cur = list; cur; cur = cur->fts_link)
752 			free(cur->fts_pointer);
753 	if (f_lomac)
754 		lomac_stop();
755 }
756 
757 /*
758  * Ordering for mastercmp:
759  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
760  * as larger than directories.  Within either group, use the sort function.
761  * All other levels use the sort function.  Error entries remain unsorted.
762  */
763 static int
764 mastercmp(const FTSENT **a, const FTSENT **b)
765 {
766 	int a_info, b_info;
767 
768 	a_info = (*a)->fts_info;
769 	if (a_info == FTS_ERR)
770 		return (0);
771 	b_info = (*b)->fts_info;
772 	if (b_info == FTS_ERR)
773 		return (0);
774 
775 	if (a_info == FTS_NS || b_info == FTS_NS)
776 		return (namecmp(*a, *b));
777 
778 	if (a_info != b_info &&
779 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
780 		if (a_info == FTS_D)
781 			return (1);
782 		if (b_info == FTS_D)
783 			return (-1);
784 	}
785 	return (sortfcn(*a, *b));
786 }
787 
788 /*
789  * Makenines() returns (10**n)-1.  This is useful for converting a width
790  * into a number that wide in decimal.
791  */
792 static u_quad_t
793 makenines(u_long n)
794 {
795 	u_long i;
796 	u_quad_t reg;
797 
798 	reg = 1;
799 	/* Use a loop instead of pow(), since all values of n are small. */
800 	for (i = 0; i < n; i++)
801 		reg *= 10;
802 	reg--;
803 
804 	return reg;
805 }
806