xref: /titanic_52/usr/src/cmd/ls/ls.c (revision 55553f719b521a0bb4deab6efc944cd30c1a56aa)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
27 /*	  All Rights Reserved  	*/
28 
29 /*	Copyright (c) 1987, 1988 Microsoft Corporation	*/
30 /*	  All Rights Reserved	*/
31 
32 #pragma ident	"%Z%%M%	%I%	%E% SMI"
33 
34 /*
35  * List files or directories
36  */
37 
38 #include <sys/param.h>
39 #include <sys/types.h>
40 #include <sys/mkdev.h>
41 #include <sys/stat.h>
42 #include <sys/acl.h>
43 
44 #include <wchar.h>
45 #include <stdio.h>
46 #include <ctype.h>
47 #include <dirent.h>
48 #include <string.h>
49 #include <locale.h>
50 #include <curses.h>
51 #include <termios.h>
52 #include <stdlib.h>
53 #include <widec.h>
54 #include <locale.h>
55 #include <wctype.h>
56 #include <pwd.h>
57 #include <grp.h>
58 #include <limits.h>
59 #include <fcntl.h>
60 #include <unistd.h>
61 #include <libgen.h>
62 #include <errno.h>
63 #include <aclutils.h>
64 #include <libnvpair.h>
65 #include <libcmdutils.h>
66 #include <attr.h>
67 
68 #ifndef STANDALONE
69 #define	TERMINFO
70 #endif
71 
72 /*
73  * -DNOTERMINFO can be defined on the cc command line to prevent
74  * the use of terminfo.  This should be done on systems not having
75  * the terminfo feature(pre 6.0 systems ?).
76  * As a result, columnar listings assume 80 columns for output,
77  * unless told otherwise via the COLUMNS environment variable.
78  */
79 #ifdef NOTERMINFO
80 #undef TERMINFO
81 #endif
82 
83 #include <term.h>
84 
85 #define	BFSIZE	16
86 /* this bit equals 1 in lflags of structure lbuf if *namep is to be used */
87 #define	ISARG	0100000
88 
89 /*
90  * this flag has been added to manipulate the display of S instead of 'l' when
91  * the file is not a regular file and when group execution bit is off
92  */
93 #define	LS_NOTREG	010000
94 
95 
96 /*
97  * Date and time formats
98  *
99  * b --- abbreviated month name
100  * e --- day number
101  * Y --- year in the form ccyy
102  * H --- hour(24-hour version)
103  * M --- minute
104  * F --- yyyy-mm-dd
105  * T --- hh:mm:ss
106  * z --- time zone as hours displacement from UTC
107  * note that %F and %z are from the ISO C99 standard and are
108  * not present in older C libraries
109  */
110 #define	FORMAT1	 " %b %e  %Y "
111 #define	FORMAT2  " %b %e %H:%M "
112 #define	FORMAT3  " %b %e %T %Y "
113 #define	FORMAT4  " %%F %%T.%.09ld %%z "
114 
115 #undef BUFSIZ
116 #define	BUFSIZ 4096
117 #define	NUMBER_WIDTH 40
118 #define	FMTSIZE 50
119 
120 struct ditem {
121 	dev_t	dev;			/* directory items device number */
122 	ino_t	ino;			/* directory items inode number */
123 	struct ditem *parent;		/* dir items ptr to its parent's info */
124 };
125 /* Holds boolean extended system attributes */
126 struct attrb {
127 	char		*name;
128 };
129 /* Holds timestamp extended system attributes */
130 struct attrtm {
131 	char		*name;
132 	uint64_t	stm;
133 	uint64_t	nstm;
134 };
135 
136 struct	lbuf	{
137 	union	{
138 		char	lname[MAXNAMLEN]; /* used for filename in a directory */
139 		char	*namep;		/* for name in ls-command; */
140 	} ln;
141 	char	ltype;		/* filetype */
142 	ino_t	lnum;		/* inode number of file */
143 	mode_t	lflags; 	/* 0777 bits used as r,w,x permissions */
144 	nlink_t	lnl;		/* number of links to file */
145 	uid_t	luid;
146 	gid_t	lgid;
147 	off_t	lsize;		/* filesize or major/minor dev numbers */
148 	blkcnt_t	lblocks;	/* number of file blocks */
149 	timestruc_t	lmtime;
150 	timestruc_t	lat;
151 	timestruc_t	lct;
152 	timestruc_t	lmt;
153 	char	*flinkto;	/* symbolic link contents */
154 	char 	acl;		/* indicate there are additional acl entries */
155 	int	cycle;		/* cycle detected flag */
156 	struct ditem *ancinfo;	/* maintains ancestor info */
157 	acl_t *aclp;		/* ACL if present */
158 	struct attrb *exttr;	/* boolean extended system attributes */
159 	struct attrtm *extm;	/* timestamp extended system attributes */
160 };
161 
162 struct dchain {
163 	char *dc_name;		/* path name */
164 	int cycle_detected;	/* cycle detected visiting this directory */
165 	struct ditem *myancinfo;	/* this directory's ancestry info */
166 	struct dchain *dc_next;	/* next directory in the chain */
167 };
168 
169 /*
170  * A numbuf_t is used when converting a number to a string representation
171  */
172 typedef char numbuf_t[NUMBER_WIDTH];
173 
174 static struct dchain *dfirst;	/* start of the dir chain */
175 static struct dchain *cdfirst;	/* start of the current dir chain */
176 static struct dchain *dtemp;	/* temporary - used for linking */
177 static char *curdir;		/* the current directory */
178 
179 static int	first = 1;	/* true if first line is not yet printed */
180 static int	nfiles = 0;	/* number of flist entries in current use */
181 static int	nargs = 0;	/* number of flist entries used for arguments */
182 static int	maxfils = 0;	/* number of flist/lbuf entries allocated */
183 static int	maxn = 0;	/* number of flist entries with lbufs asigned */
184 static int	quantn = 64;	/* allocation growth quantum */
185 
186 static struct lbuf	*nxtlbf;	/* ptr to next lbuf to be assigned */
187 static struct lbuf	**flist;	/* ptr to list of lbuf pointers */
188 static struct lbuf	*gstat(char *, int, struct ditem *);
189 static char		*getname(uid_t);
190 static char		*getgroup(gid_t);
191 static char		*makename(char *, char *);
192 static void		pentry(struct lbuf *);
193 static void		column(void);
194 static void		pmode(mode_t aflag);
195 static void		selection(int *);
196 static void		new_line(void);
197 static void		rddir(char *, struct ditem *);
198 static int		strcol(unsigned char *);
199 static void		pem(struct lbuf **, struct lbuf **, int);
200 static void		pdirectory(char *, int, int, int, struct ditem *);
201 static struct cachenode *findincache(struct cachenode **, long);
202 static void		csi_pprintf(unsigned char *);
203 static void		pprintf(char *, char *);
204 static int		compar(struct lbuf **pp1, struct lbuf **pp2);
205 static char 		*number_to_scaled_string(numbuf_t buf,
206 			    unsigned long long number,
207 			    long scale);
208 static void		record_ancestry(char *, struct stat *, struct lbuf *,
209 			    int, struct ditem *);
210 
211 static int		aflg;
212 static int		atflg;
213 static int		bflg;
214 static int		cflg;
215 static int		dflg;
216 static int		eflg;
217 static int		fflg;
218 static int		gflg;
219 static int		hflg;
220 static int		iflg;
221 static int		lflg;
222 static int		mflg;
223 static int		nflg;
224 static int		oflg;
225 static int		pflg;
226 static int		qflg;
227 static int		rflg = 1; /* init to 1 for special use in compar */
228 static int		sflg;
229 static int		tflg;
230 static int		uflg;
231 static int		xflg;
232 static int		Aflg;
233 static int		Cflg;
234 static int		Eflg;
235 static int		Fflg;
236 static int		Hflg;
237 static int		Lflg;
238 static int		Rflg;
239 static int		Sflg;
240 static int		vflg;
241 static int		Vflg;
242 static int		saflg;		/* boolean extended system attr. */
243 static int		sacnt;		/* number of extended system attr. */
244 static int		copt;
245 static int		vopt;
246 static int		tmflg;		/* create time ext. system attr. */
247 static int		ctm;
248 static int		atm;
249 static int		mtm;
250 static int		crtm;
251 static int		alltm;
252 static long		hscale;
253 static mode_t		flags;
254 static int		err = 0;	/* Contains return code */
255 
256 static uid_t		lastuid	= (uid_t)-1;
257 static gid_t		lastgid = (gid_t)-1;
258 static char		*lastuname = NULL;
259 static char		*lastgname = NULL;
260 
261 /* statreq > 0 if any of sflg, (n)lflg, tflg, Sflg are on */
262 static int		statreq;
263 
264 static char		*dotp = ".";
265 
266 static u_longlong_t 	tblocks; /* number of blocks of files in a directory */
267 static time_t		year, now;
268 
269 static int		num_cols = 80;
270 static int		colwidth;
271 static int		filewidth;
272 static int		fixedwidth;
273 static int		nomocore;
274 static int		curcol;
275 
276 static struct	winsize	win;
277 
278 static char	time_buf[FMTSIZE];	/* array to hold day and time */
279 
280 #define	NOTWORKINGDIR(d, l)	(((l) < 2) || \
281 				    (strcmp((d) + (l) - 2, "/.") != 0))
282 
283 #define	NOTPARENTDIR(d, l)	(((l) < 3) || \
284 				    (strcmp((d) + (l) - 3, "/..") != 0))
285 /* Extended system attributes support */
286 static int get_sysxattr(char *, struct lbuf *);
287 static void set_sysattrb_display(char *, boolean_t, struct lbuf *);
288 static void set_sysattrtm_display(char *, struct lbuf *);
289 static void format_time(const char *, time_t);
290 static void format_etime(const char *, time_t, time_t);
291 static void print_time(struct lbuf *);
292 static void format_attrtime(struct lbuf *);
293 static void *xmalloc(size_t, struct lbuf *);
294 static void free_sysattr(struct lbuf *);
295 static nvpair_t *pair;
296 static nvlist_t	*response;
297 
298 int
299 main(int argc, char *argv[])
300 {
301 	int		c;
302 	int		i;
303 	int		width;
304 	int		amino = 0;
305 	int		opterr = 0;
306 	struct lbuf	*ep;
307 	struct lbuf	lb;
308 	struct ditem	*myinfo;
309 
310 	(void) setlocale(LC_ALL, "");
311 #if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
312 #define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
313 #endif
314 	(void) textdomain(TEXT_DOMAIN);
315 #ifdef STANDALONE
316 	if (argv[0][0] == '\0')
317 		argc = getargv("ls", &argv, 0);
318 #endif
319 
320 	lb.lmtime.tv_sec = time(NULL);
321 	lb.lmtime.tv_nsec = 0;
322 	year = lb.lmtime.tv_sec - 6L*30L*24L*60L*60L; /* 6 months ago */
323 	now = lb.lmtime.tv_sec + 60;
324 	if (isatty(1)) {
325 		Cflg = 1;
326 		mflg = 0;
327 	}
328 
329 	while ((c = getopt(argc, argv,
330 	    "aAbcCdeEfFghHilLmnopqrRsStux1@vV/:%:")) != EOF)
331 		switch (c) {
332 		case 'a':
333 			aflg++;
334 			continue;
335 		case 'A':
336 			Aflg++;
337 			continue;
338 		case 'b':
339 			bflg = 1;
340 			qflg = 0;
341 			continue;
342 		case 'c':
343 			uflg = 0;
344 			atm = 0;
345 			ctm = 0;
346 			mtm = 0;
347 			crtm = 0;
348 			cflg++;
349 			continue;
350 		case 'C':
351 			Cflg = 1;
352 			mflg = 0;
353 #ifdef XPG4
354 			lflg = 0;
355 #endif
356 			continue;
357 		case 'd':
358 			dflg++;
359 			continue;
360 		case 'e':
361 			eflg++;
362 			lflg++;
363 			statreq++;
364 			Eflg = 0;
365 			continue;
366 		case 'E':
367 			Eflg++;
368 			lflg++;
369 			statreq++;
370 			eflg = 0;
371 			continue;
372 		case 'f':
373 			fflg++;
374 			continue;
375 		case 'F':
376 			Fflg++;
377 			statreq++;
378 			continue;
379 		case 'g':
380 			gflg++;
381 			lflg++;
382 			statreq++;
383 			continue;
384 		case 'h':
385 			hflg++;
386 			hscale = 1024;
387 			continue;
388 		case 'H':
389 			Hflg++;
390 			/* -H and -L are mutually exclusive */
391 			Lflg = 0;
392 			continue;
393 		case 'i':
394 			iflg++;
395 			continue;
396 		case 'l':
397 			lflg++;
398 			statreq++;
399 			Cflg = 0;
400 			xflg = 0;
401 			mflg = 0;
402 			atflg = 0;
403 			continue;
404 		case 'L':
405 			Lflg++;
406 			/* -H and -L are mutually exclusive */
407 			Hflg = 0;
408 			continue;
409 		case 'm':
410 			Cflg = 0;
411 			mflg = 1;
412 #ifdef XPG4
413 			lflg = 0;
414 #endif
415 			continue;
416 		case 'n':
417 			nflg++;
418 			lflg++;
419 			statreq++;
420 			Cflg = 0;
421 			xflg = 0;
422 			mflg = 0;
423 			atflg = 0;
424 			continue;
425 		case 'o':
426 			oflg++;
427 			lflg++;
428 			statreq++;
429 			continue;
430 		case 'p':
431 			pflg++;
432 			statreq++;
433 			continue;
434 		case 'q':
435 			qflg = 1;
436 			bflg = 0;
437 			continue;
438 		case 'r':
439 			rflg = -1;
440 			continue;
441 		case 'R':
442 			Rflg++;
443 			statreq++;
444 			continue;
445 		case 's':
446 			sflg++;
447 			statreq++;
448 			continue;
449 		case 'S':
450 			tflg = 0;
451 			Sflg++;
452 			statreq++;
453 			continue;
454 		case 't':
455 			Sflg = 0;
456 			tflg++;
457 			statreq++;
458 			continue;
459 		case 'u':
460 			cflg = 0;
461 			atm = 0;
462 			ctm = 0;
463 			mtm = 0;
464 			crtm = 0;
465 			uflg++;
466 			continue;
467 		case 'V':
468 			Vflg++;
469 			/*FALLTHROUGH*/
470 		case 'v':
471 			vflg++;
472 #if !defined(XPG4)
473 			if (lflg)
474 				continue;
475 #endif
476 			lflg++;
477 			statreq++;
478 			Cflg = 0;
479 			xflg = 0;
480 			mflg = 0;
481 			continue;
482 		case 'x':
483 			xflg = 1;
484 			Cflg = 1;
485 			mflg = 0;
486 #ifdef XPG4
487 			lflg = 0;
488 #endif
489 			continue;
490 		case '1':
491 			Cflg = 0;
492 			continue;
493 		case '@':
494 #if !defined(XPG4)
495 			/*
496 			 * -l has precedence over -@
497 			 */
498 			if (lflg)
499 				continue;
500 #endif
501 			atflg++;
502 			lflg++;
503 			statreq++;
504 			Cflg = 0;
505 			xflg = 0;
506 			mflg = 0;
507 			continue;
508 		case '/':
509 			saflg++;
510 			if (optarg != NULL) {
511 				if (strcmp(optarg, "c") == 0) {
512 					copt++;
513 					vopt = 0;
514 				} else if (strcmp(optarg, "v") == 0) {
515 					vopt++;
516 					copt = 0;
517 				} else
518 					opterr++;
519 			} else
520 				opterr++;
521 			lflg++;
522 			statreq++;
523 			Cflg = 0;
524 			xflg = 0;
525 			mflg = 0;
526 			continue;
527 		case '%':
528 			tmflg++;
529 			if (optarg != NULL) {
530 				if (strcmp(optarg, "ctime") == 0) {
531 					ctm++;
532 					atm = 0;
533 					mtm = 0;
534 					crtm = 0;
535 				} else if (strcmp(optarg, "atime") == 0) {
536 					atm++;
537 					ctm = 0;
538 					mtm = 0;
539 					crtm = 0;
540 					uflg = 0;
541 					cflg = 0;
542 				} else if (strcmp(optarg, "mtime") == 0) {
543 					mtm++;
544 					atm = 0;
545 					ctm = 0;
546 					crtm = 0;
547 					uflg = 0;
548 					cflg = 0;
549 				} else if (strcmp(optarg, "crtime") == 0) {
550 					crtm++;
551 					atm = 0;
552 					ctm = 0;
553 					mtm = 0;
554 					uflg = 0;
555 					cflg = 0;
556 				} else if (strcmp(optarg, "all") == 0) {
557 					alltm++;
558 					atm = 0;
559 					ctm = 0;
560 					mtm = 0;
561 					crtm = 0;
562 				} else
563 					opterr++;
564 			} else
565 				opterr++;
566 
567 			Sflg = 0;
568 			statreq++;
569 			mflg = 0;
570 			continue;
571 		case '?':
572 			opterr++;
573 			continue;
574 		}
575 	if (opterr) {
576 		(void) fprintf(stderr, gettext(
577 		    "usage: ls -aAbcCdeEfFghHilLmnopqrRsStuxvV1@/%[c | v]"
578 		    "%%[atime | crtime | ctime | mtime | all]"
579 		    " [files]\n"));
580 		exit(2);
581 	}
582 
583 	if (fflg) {
584 		aflg++;
585 		lflg = 0;
586 		sflg = 0;
587 		tflg = 0;
588 		Sflg = 0;
589 		statreq = 0;
590 	}
591 
592 	fixedwidth = 2;
593 	if (pflg || Fflg)
594 		fixedwidth++;
595 	if (iflg)
596 		fixedwidth += 11;
597 	if (sflg)
598 		fixedwidth += 5;
599 
600 	if (lflg) {
601 		if (!gflg && !oflg)
602 			gflg = oflg = 1;
603 		else
604 		if (gflg && oflg)
605 			gflg = oflg = 0;
606 		Cflg = mflg = 0;
607 	}
608 
609 	if (Cflg || mflg) {
610 		char *clptr;
611 		if ((clptr = getenv("COLUMNS")) != NULL)
612 			num_cols = atoi(clptr);
613 #ifdef TERMINFO
614 		else {
615 			if (ioctl(1, TIOCGWINSZ, &win) != -1)
616 				num_cols = (win.ws_col == 0 ? 80 : win.ws_col);
617 		}
618 #endif
619 		if (num_cols < 20 || num_cols > 1000)
620 			/* assume it is an error */
621 			num_cols = 80;
622 	}
623 
624 	/* allocate space for flist and the associated	*/
625 	/* data structures (lbufs)			*/
626 	maxfils = quantn;
627 	if (((flist = malloc(maxfils * sizeof (struct lbuf *))) == NULL) ||
628 	    ((nxtlbf = malloc(quantn * sizeof (struct lbuf))) == NULL)) {
629 		perror("ls");
630 		exit(2);
631 	}
632 	if ((amino = (argc-optind)) == 0) {
633 					/*
634 					 * case when no names are given
635 					 * in ls-command and current
636 					 * directory is to be used
637 					 */
638 		argv[optind] = dotp;
639 	}
640 
641 	for (i = 0; i < (amino ? amino : 1); i++) {
642 
643 		/*
644 		 * If we are recursing, we need to make sure we don't
645 		 * get into an endless loop.  To keep track of the inodes
646 		 * (actually, just the directories) visited, we
647 		 * maintain a directory ancestry list for a file
648 		 * hierarchy.  As we go deeper into the hierarchy,
649 		 * a parent directory passes its directory list
650 		 * info (device id, inode number, and a pointer to
651 		 * its parent) to each of its children.  As we
652 		 * process a child that is a directory, we save
653 		 * its own personal directory list info.  We then
654 		 * check to see if the child has already been
655 		 * processed by comparing its device id and inode
656 		 * number from its own personal directory list info
657 		 * to that of each of its ancestors.  If there is a
658 		 * match, then we know we've detected a cycle.
659 		 */
660 		if (Rflg) {
661 			/*
662 			 * This is the first parent in this lineage
663 			 * (first in a directory hierarchy), so
664 			 * this parent's parent doesn't exist.  We
665 			 * only initialize myinfo when we are
666 			 * recursing, otherwise it's not used.
667 			 */
668 			if ((myinfo = (struct ditem *)malloc(
669 			    sizeof (struct ditem))) == NULL) {
670 				perror("ls");
671 				exit(2);
672 			} else {
673 				myinfo->dev = 0;
674 				myinfo->ino = 0;
675 				myinfo->parent = NULL;
676 			}
677 		}
678 
679 		if (Cflg || mflg) {
680 			width = strcol((unsigned char *)argv[optind]);
681 			if (width > filewidth)
682 				filewidth = width;
683 		}
684 		if ((ep = gstat((*argv[optind] ? argv[optind] : dotp),
685 		    1, myinfo)) == NULL) {
686 			if (nomocore)
687 				exit(2);
688 			err = 2;
689 			optind++;
690 			continue;
691 		}
692 		ep->ln.namep = (*argv[optind] ? argv[optind] : dotp);
693 		ep->lflags |= ISARG;
694 		optind++;
695 		nargs++;	/* count good arguments stored in flist */
696 	}
697 	colwidth = fixedwidth + filewidth;
698 	qsort(flist, (unsigned)nargs, sizeof (struct lbuf *),
699 	    (int (*)(const void *, const void *))compar);
700 	for (i = 0; i < nargs; i++) {
701 		if (flist[i]->ltype == 'd' && dflg == 0 || fflg)
702 			break;
703 	}
704 	pem(&flist[0], &flist[i], 0);
705 	for (; i < nargs; i++) {
706 		pdirectory(flist[i]->ln.namep, Rflg ||
707 		    (amino > 1), nargs, 0, flist[i]->ancinfo);
708 		if (nomocore)
709 			exit(2);
710 		/* -R: print subdirectories found */
711 		while (dfirst || cdfirst) {
712 			/* Place direct subdirs on front in right order */
713 			while (cdfirst) {
714 				/* reverse cdfirst onto front of dfirst */
715 				dtemp = cdfirst;
716 				cdfirst = cdfirst -> dc_next;
717 				dtemp -> dc_next = dfirst;
718 				dfirst = dtemp;
719 			}
720 			/* take off first dir on dfirst & print it */
721 			dtemp = dfirst;
722 			dfirst = dfirst->dc_next;
723 			pdirectory(dtemp->dc_name, 1, nargs,
724 			    dtemp->cycle_detected, dtemp->myancinfo);
725 			if (nomocore)
726 				exit(2);
727 			free(dtemp->dc_name);
728 			free(dtemp);
729 		}
730 	}
731 	return (err);
732 }
733 
734 /*
735  * pdirectory: print the directory name, labelling it if title is
736  * nonzero, using lp as the place to start reading in the dir.
737  */
738 static void
739 pdirectory(char *name, int title, int lp, int cdetect, struct ditem *myinfo)
740 {
741 	struct dchain *dp;
742 	struct lbuf *ap;
743 	char *pname;
744 	int j;
745 
746 	filewidth = 0;
747 	curdir = name;
748 	if (title) {
749 		if (!first)
750 			(void) putc('\n', stdout);
751 		pprintf(name, ":");
752 		new_line();
753 	}
754 	/*
755 	 * If there was a cycle detected, then notify and don't report
756 	 * further.
757 	 */
758 	if (cdetect) {
759 		if (lflg || sflg) {
760 			curcol += printf(gettext("total %d"), 0);
761 			new_line();
762 		}
763 		(void) fprintf(stderr, gettext(
764 		    "ls: cycle detected for %s\n"), name);
765 		return;
766 	}
767 
768 	nfiles = lp;
769 	rddir(name, myinfo);
770 	if (nomocore)
771 		return;
772 	if (fflg == 0)
773 		qsort(&flist[lp], (unsigned)(nfiles - lp),
774 		    sizeof (struct lbuf *),
775 		    (int (*)(const void *, const void *))compar);
776 	if (Rflg) {
777 		for (j = nfiles - 1; j >= lp; j--) {
778 			ap = flist[j];
779 			if (ap->ltype == 'd' && strcmp(ap->ln.lname, ".") &&
780 			    strcmp(ap->ln.lname, "..")) {
781 				dp = malloc(sizeof (struct dchain));
782 				if (dp == NULL) {
783 					perror("ls");
784 					exit(2);
785 				}
786 				pname = makename(curdir, ap->ln.lname);
787 				if ((dp->dc_name = strdup(pname)) == NULL) {
788 					perror("ls");
789 					exit(2);
790 				}
791 				dp->cycle_detected = ap->cycle;
792 				dp->myancinfo = ap->ancinfo;
793 				dp->dc_next = dfirst;
794 				dfirst = dp;
795 			}
796 		}
797 	}
798 	if (lflg || sflg) {
799 		curcol += printf(gettext("total %llu"), tblocks);
800 		new_line();
801 	}
802 	pem(&flist[lp], &flist[nfiles], lflg||sflg);
803 }
804 
805 /*
806  * pem: print 'em. Print a list of files (e.g. a directory) bounded
807  * by slp and lp.
808  */
809 static void
810 pem(struct lbuf **slp, struct lbuf **lp, int tot_flag)
811 {
812 	long row, nrows, i;
813 	int col, ncols;
814 	struct lbuf **ep;
815 
816 	if (Cflg || mflg) {
817 		if (colwidth > num_cols) {
818 			ncols = 1;
819 		} else {
820 			ncols = num_cols / colwidth;
821 		}
822 	}
823 
824 	if (ncols == 1 || mflg || xflg || !Cflg) {
825 		for (ep = slp; ep < lp; ep++)
826 			pentry(*ep);
827 		new_line();
828 		return;
829 	}
830 	/* otherwise print -C columns */
831 	if (tot_flag) {
832 		slp--;
833 		row = 1;
834 	}
835 	else
836 		row = 0;
837 
838 	nrows = (lp - slp - 1) / ncols + 1;
839 	for (i = 0; i < nrows; i++, row++) {
840 		for (col = 0; col < ncols; col++) {
841 			ep = slp + (nrows * col) + row;
842 			if (ep < lp)
843 				pentry(*ep);
844 		}
845 		new_line();
846 	}
847 }
848 
849 /*
850  * print one output entry;
851  * if uid/gid is not found in the appropriate
852  * file(passwd/group), then print uid/gid instead of
853  * user/group name;
854  */
855 static void
856 pentry(struct lbuf *ap)
857 {
858 	struct lbuf *p;
859 	numbuf_t hbuf;
860 	char buf[BUFSIZ];
861 	char *dmark = "";	/* Used if -p or -F option active */
862 	char *cp;
863 
864 	p = ap;
865 	column();
866 	if (iflg)
867 		if (mflg && !lflg)
868 			curcol += printf("%llu ", (long long)p->lnum);
869 		else
870 			curcol += printf("%10llu ", (long long)p->lnum);
871 	if (sflg)
872 		curcol += printf((mflg && !lflg) ? "%lld " :
873 		    (p->lblocks < 10000) ? "%4lld " : "%lld ",
874 		    (p->ltype != 'b' && p->ltype != 'c') ?
875 		    p->lblocks : 0LL);
876 	if (lflg) {
877 		(void) putchar(p->ltype);
878 		curcol++;
879 		pmode(p->lflags);
880 
881 		/* ACL: additional access mode flag */
882 		(void) putchar(p->acl);
883 		curcol++;
884 
885 		curcol += printf("%3lu ", (ulong_t)p->lnl);
886 		if (oflg)
887 			if (!nflg) {
888 				cp = getname(p->luid);
889 				curcol += printf("%-8s ", cp);
890 			} else
891 				curcol += printf("%-8lu ", (ulong_t)p->luid);
892 		if (gflg)
893 			if (!nflg) {
894 				cp = getgroup(p->lgid);
895 				curcol += printf("%-8s ", cp);
896 			} else
897 				curcol += printf("%-8lu ", (ulong_t)p->lgid);
898 		if (p->ltype == 'b' || p->ltype == 'c') {
899 			curcol += printf("%3u, %2u",
900 			    (uint_t)major((dev_t)p->lsize),
901 			    (uint_t)minor((dev_t)p->lsize));
902 		} else if (hflg && (p->lsize >= hscale)) {
903 			curcol += printf("%7s",
904 			    number_to_scaled_string(hbuf, p->lsize, hscale));
905 		} else {
906 			curcol += printf((p->lsize < (off_t)10000000) ?
907 			    "%7lld" : "%lld", p->lsize);
908 		}
909 		if (eflg)
910 			format_time(FORMAT3, p->lmtime.tv_sec);
911 		else if (Eflg)
912 			/* fill in nanoseconds first */
913 			format_etime(FORMAT4, p->lmtime.tv_sec,
914 			    p->lmtime.tv_nsec);
915 		else {
916 			if ((p->lmtime.tv_sec < year) ||
917 			    (p->lmtime.tv_sec > now))
918 				format_time(FORMAT1, p->lmtime.tv_sec);
919 			else
920 				format_time(FORMAT2, p->lmtime.tv_sec);
921 		}
922 		/* format extended system attribute time */
923 		if (tmflg && crtm)
924 			format_attrtime(p);
925 
926 		curcol += printf("%s", time_buf);
927 
928 	}
929 	/*
930 	 * prevent both "->" and trailing marks
931 	 * from appearing
932 	 */
933 
934 	if (pflg && p->ltype == 'd')
935 		dmark = "/";
936 
937 	if (Fflg && !(lflg && p->flinkto)) {
938 		if (p->ltype == 'd')
939 			dmark = "/";
940 		else if (p->ltype == 'D')
941 			dmark = ">";
942 		else if (p->ltype == 'p')
943 			dmark = "|";
944 		else if (p->ltype == 'l')
945 			dmark = "@";
946 		else if (p->ltype == 's')
947 			dmark = "=";
948 		else if (p->lflags & (S_IXUSR|S_IXGRP|S_IXOTH))
949 			dmark = "*";
950 		else
951 			dmark = "";
952 	}
953 
954 	if (lflg && p->flinkto) {
955 		(void) strncpy(buf, " -> ", 4);
956 		(void) strcpy(buf + 4, p->flinkto);
957 		dmark = buf;
958 	}
959 
960 	if (p->lflags & ISARG) {
961 		if (qflg || bflg)
962 			pprintf(p->ln.namep, dmark);
963 		else {
964 			(void) printf("%s%s", p->ln.namep, dmark);
965 			curcol += strcol((unsigned char *)p->ln.namep);
966 			curcol += strcol((unsigned char *)dmark);
967 		}
968 	} else {
969 		if (qflg || bflg)
970 			pprintf(p->ln.lname, dmark);
971 		else {
972 			(void) printf("%s%s", p->ln.lname, dmark);
973 			curcol += strcol((unsigned char *)p->ln.lname);
974 			curcol += strcol((unsigned char *)dmark);
975 		}
976 	}
977 
978 	/* Display extended system attributes */
979 	if (saflg) {
980 		int i;
981 
982 		new_line();
983 		(void) printf("	\t{");
984 		if (p->exttr != NULL) {
985 			int k = 0;
986 			for (i = 0; i < sacnt; i++) {
987 				if (p->exttr[i].name != NULL)
988 					k++;
989 			}
990 			for (i = 0; i < sacnt; i++) {
991 				if (p->exttr[i].name != NULL) {
992 					(void) printf("%s", p->exttr[i].name);
993 					k--;
994 					if (vopt && (k != 0))
995 						(void) printf(",");
996 				}
997 			}
998 		}
999 		(void) printf("}\n");
1000 	}
1001 	/* Display file timestamps and extended system attribute timestamps */
1002 	if (tmflg && alltm) {
1003 		new_line();
1004 		print_time(p);
1005 		new_line();
1006 	}
1007 	if (vflg) {
1008 		new_line();
1009 		if (p->aclp) {
1010 			acl_printacl(p->aclp, num_cols, Vflg);
1011 		}
1012 	}
1013 	/* Free extended system attribute lists */
1014 	if (saflg || tmflg)
1015 		free_sysattr(p);
1016 }
1017 
1018 /* print various r,w,x permissions */
1019 static void
1020 pmode(mode_t aflag)
1021 {
1022 	/* these arrays are declared static to allow initializations */
1023 	static int	m0[] = { 1, S_IRUSR, 'r', '-' };
1024 	static int	m1[] = { 1, S_IWUSR, 'w', '-' };
1025 	static int	m2[] = { 3, S_ISUID|S_IXUSR, 's', S_IXUSR,
1026 	    'x', S_ISUID, 'S', '-' };
1027 	static int	m3[] = { 1, S_IRGRP, 'r', '-' };
1028 	static int	m4[] = { 1, S_IWGRP, 'w', '-' };
1029 	static int	m5[] = { 4, S_ISGID|S_IXGRP, 's', S_IXGRP,
1030 				'x', S_ISGID|LS_NOTREG, 'S',
1031 #ifdef XPG4
1032 		S_ISGID, 'L', '-'};
1033 #else
1034 		S_ISGID, 'l', '-'};
1035 #endif
1036 	static int	m6[] = { 1, S_IROTH, 'r', '-' };
1037 	static int	m7[] = { 1, S_IWOTH, 'w', '-' };
1038 	static int	m8[] = { 3, S_ISVTX|S_IXOTH, 't', S_IXOTH,
1039 	    'x', S_ISVTX, 'T', '-'};
1040 
1041 	static int *m[] = { m0, m1, m2, m3, m4, m5, m6, m7, m8};
1042 
1043 	int **mp;
1044 
1045 	flags = aflag;
1046 	for (mp = &m[0]; mp < &m[sizeof (m) / sizeof (m[0])]; mp++)
1047 		selection(*mp);
1048 }
1049 
1050 static void
1051 selection(int *pairp)
1052 {
1053 	int n;
1054 
1055 	n = *pairp++;
1056 	while (n-->0) {
1057 		if ((flags & *pairp) == *pairp) {
1058 			pairp++;
1059 			break;
1060 		} else {
1061 			pairp += 2;
1062 		}
1063 	}
1064 	(void) putchar(*pairp);
1065 	curcol++;
1066 }
1067 
1068 /*
1069  * column: get to the beginning of the next column.
1070  */
1071 static void
1072 column(void)
1073 {
1074 	if (curcol == 0)
1075 		return;
1076 	if (mflg) {
1077 		(void) putc(',', stdout);
1078 		curcol++;
1079 		if (curcol + colwidth + 2 > num_cols) {
1080 			(void) putc('\n', stdout);
1081 			curcol = 0;
1082 			return;
1083 		}
1084 		(void) putc(' ', stdout);
1085 		curcol++;
1086 		return;
1087 	}
1088 	if (Cflg == 0) {
1089 		(void) putc('\n', stdout);
1090 		curcol = 0;
1091 		return;
1092 	}
1093 	if ((curcol / colwidth + 2) * colwidth > num_cols) {
1094 		(void) putc('\n', stdout);
1095 		curcol = 0;
1096 		return;
1097 	}
1098 	do {
1099 		(void) putc(' ', stdout);
1100 		curcol++;
1101 	} while (curcol % colwidth);
1102 }
1103 
1104 static void
1105 new_line(void)
1106 {
1107 	if (curcol) {
1108 		first = 0;
1109 		(void) putc('\n', stdout);
1110 		curcol = 0;
1111 	}
1112 }
1113 
1114 /*
1115  * read each filename in directory dir and store its
1116  * status in flist[nfiles]
1117  * use makename() to form pathname dir/filename;
1118  */
1119 static void
1120 rddir(char *dir, struct ditem *myinfo)
1121 {
1122 	struct dirent *dentry;
1123 	DIR *dirf;
1124 	int j;
1125 	struct lbuf *ep;
1126 	int width;
1127 
1128 	if ((dirf = opendir(dir)) == NULL) {
1129 		(void) fflush(stdout);
1130 		perror(dir);
1131 		err = 2;
1132 		return;
1133 	} else {
1134 		tblocks = 0;
1135 		for (;;) {
1136 			errno = 0;
1137 			if ((dentry = readdir(dirf)) == NULL)
1138 				break;
1139 			if (aflg == 0 && dentry->d_name[0] == '.' &&
1140 			    (Aflg == 0 ||
1141 			    dentry->d_name[1] == '\0' ||
1142 			    dentry->d_name[1] == '.' &&
1143 			    dentry->d_name[2] == '\0'))
1144 				/*
1145 				 * check for directory items '.', '..',
1146 				 *  and items without valid inode-number;
1147 				 */
1148 				continue;
1149 
1150 			if (Cflg || mflg) {
1151 				width = strcol((unsigned char *)dentry->d_name);
1152 				if (width > filewidth)
1153 					filewidth = width;
1154 			}
1155 			ep = gstat(makename(dir, dentry->d_name), 0, myinfo);
1156 			if (ep == NULL) {
1157 				if (nomocore)
1158 					exit(2);
1159 				continue;
1160 			} else {
1161 				ep->lnum = dentry->d_ino;
1162 				for (j = 0; dentry->d_name[j] != '\0'; j++)
1163 					ep->ln.lname[j] = dentry->d_name[j];
1164 				ep->ln.lname[j] = '\0';
1165 			}
1166 		}
1167 		if (errno) {
1168 			int sav_errno = errno;
1169 
1170 			(void) fprintf(stderr,
1171 			    gettext("ls: error reading directory %s: %s\n"),
1172 			    dir, strerror(sav_errno));
1173 		}
1174 		(void) closedir(dirf);
1175 		colwidth = fixedwidth + filewidth;
1176 	}
1177 }
1178 
1179 /*
1180  * Attaching a link to an inode's ancestors.  Search
1181  * through the ancestors to check for cycles (an inode which
1182  * we have already tracked in this inodes ancestry).  If a cycle
1183  * is detected, set the exit code and record the fact so that
1184  * it is reported at the right time when printing the directory.
1185  * In addition, set the exit code.  Note:  If the -a flag was
1186  * specified, we don't want to check for cycles for directories
1187  * ending in '/.' or '/..' unless they were specified on the
1188  * command line.
1189  */
1190 static void
1191 record_ancestry(char *file, struct stat *pstatb, struct lbuf *rep,
1192     int argfl, struct ditem *myparent)
1193 {
1194 	size_t		file_len;
1195 	struct ditem	*myinfo;
1196 	struct ditem	*tptr;
1197 
1198 	file_len = strlen(file);
1199 	if (!aflg || argfl || (NOTWORKINGDIR(file, file_len) &&
1200 	    NOTPARENTDIR(file, file_len))) {
1201 		/*
1202 		 * Add this inode's ancestry
1203 		 * info and insert it into the
1204 		 * ancestry list by pointing
1205 		 * back to its parent.  We save
1206 		 * it (in rep) with the other info
1207 		 * we're gathering for this inode.
1208 		 */
1209 		if ((myinfo = malloc(
1210 		    sizeof (struct ditem))) == NULL) {
1211 			perror("ls");
1212 			exit(2);
1213 		}
1214 		myinfo->dev = pstatb->st_dev;
1215 		myinfo->ino = pstatb->st_ino;
1216 		myinfo->parent = myparent;
1217 		rep->ancinfo = myinfo;
1218 
1219 		/*
1220 		 * If this node has the same device id and
1221 		 * inode number of one of its ancestors,
1222 		 * then we've detected a cycle.
1223 		 */
1224 		if (myparent != NULL) {
1225 			for (tptr = myparent; tptr->parent != NULL;
1226 			    tptr = tptr->parent) {
1227 				if ((tptr->dev == pstatb->st_dev) &&
1228 				    (tptr->ino == pstatb->st_ino)) {
1229 					/*
1230 					 * Cycle detected for this
1231 					 * directory.  Record the fact
1232 					 * it is a cycle so we don't
1233 					 * try to process this
1234 					 * directory as we are
1235 					 * walking through the
1236 					 * list of directories.
1237 					 */
1238 					rep->cycle = 1;
1239 					err = 2;
1240 					break;
1241 				}
1242 			}
1243 		}
1244 	}
1245 }
1246 
1247 /*
1248  * Do re-calculate the mode for group for ACE_T type of acls.
1249  * This is because, if the server's FS happens to be UFS, supporting
1250  * POSIX ACL's, then it does a special calculation of group mode
1251  * to be the bitwise OR of CLASS_OBJ and GROUP_OBJ (see PSARC/2001/717.)
1252  *
1253  * This algorithm is from the NFSv4 ACL Draft. Here a part of that
1254  * algorithm is used for the group mode calculation only.
1255  * What is modified here from the algorithm is that only the
1256  * entries with flags ACE_GROUP are considered. For each entry
1257  * with ACE_GROUP flag, the first occurance of a specific access
1258  * is checked if it is allowed.
1259  * We are not interested in perms for owner@ and other@, as they
1260  * were taken from st_mode value.
1261  * We are not interested in a_who field of ACE, as we need just
1262  * unix mode bits for the group.
1263  */
1264 int
1265 grp_mask_to_mode(acl_t *acep)
1266 {
1267 	int mode = 0, seen = 0;
1268 	int acecnt;
1269 	ace_t *ap;
1270 
1271 	acecnt = acl_cnt(acep);
1272 	for (ap = (ace_t *)acl_data(acep); acecnt--; ap++) {
1273 		if ((ap->a_type == ACE_ACCESS_ALLOWED_ACE_TYPE ||
1274 		    ap->a_type == ACE_ACCESS_DENIED_ACE_TYPE) &&
1275 		    !(ap->a_flags & ACE_INHERIT_ONLY_ACE)) {
1276 			if (ap->a_flags & ACE_GROUP) {
1277 				if (ap->a_access_mask & ACE_READ_DATA) {
1278 					if (!(seen & S_IRGRP)) {
1279 						seen |= S_IRGRP;
1280 						if (ap->a_type ==
1281 						    ACE_ACCESS_ALLOWED_ACE_TYPE)
1282 							mode |= S_IRGRP;
1283 					}
1284 				}
1285 				if (ap->a_access_mask & ACE_WRITE_DATA) {
1286 					if (!(seen & S_IWGRP)) {
1287 						seen |= S_IWGRP;
1288 						if (ap->a_type ==
1289 						    ACE_ACCESS_ALLOWED_ACE_TYPE)
1290 							mode |= S_IWGRP;
1291 					}
1292 				}
1293 				if (ap->a_access_mask & ACE_EXECUTE) {
1294 					if (!(seen & S_IXGRP)) {
1295 						seen |= S_IXGRP;
1296 						if (ap->a_type ==
1297 						    ACE_ACCESS_ALLOWED_ACE_TYPE)
1298 							mode |= S_IXGRP;
1299 					}
1300 				}
1301 			}
1302 		}
1303 	}
1304 	return (mode);
1305 }
1306 
1307 /*
1308  * get status of file and recomputes tblocks;
1309  * argfl = 1 if file is a name in ls-command and = 0
1310  * for filename in a directory whose name is an
1311  * argument in the command;
1312  * stores a pointer in flist[nfiles] and
1313  * returns that pointer;
1314  * returns NULL if failed;
1315  */
1316 static struct lbuf *
1317 gstat(char *file, int argfl, struct ditem *myparent)
1318 {
1319 	struct stat statb, statb1;
1320 	struct lbuf *rep;
1321 	char buf[BUFSIZ];
1322 	ssize_t cc;
1323 	int (*statf)() = ((Lflg) || (Hflg && argfl)) ? stat : lstat;
1324 	int aclcnt;
1325 	int error;
1326 	aclent_t *tp;
1327 	o_mode_t groupperm, mask;
1328 	int grouppermfound, maskfound;
1329 
1330 	if (nomocore)
1331 		return (NULL);
1332 
1333 	if (nfiles >= maxfils) {
1334 		/*
1335 		 * all flist/lbuf pair assigned files, time to get some
1336 		 * more space
1337 		 */
1338 		maxfils += quantn;
1339 		if (((flist = realloc(flist,
1340 		    maxfils * sizeof (struct lbuf *))) == NULL) ||
1341 		    ((nxtlbf = malloc(quantn *
1342 		    sizeof (struct lbuf))) == NULL)) {
1343 			perror("ls");
1344 			nomocore = 1;
1345 			return (NULL);
1346 		}
1347 	}
1348 
1349 	/*
1350 	 * nfiles is reset to nargs for each directory
1351 	 * that is given as an argument maxn is checked
1352 	 * to prevent the assignment of an lbuf to a flist entry
1353 	 * that already has one assigned.
1354 	 */
1355 	if (nfiles >= maxn) {
1356 		rep = nxtlbf++;
1357 		flist[nfiles++] = rep;
1358 		maxn = nfiles;
1359 	} else {
1360 		rep = flist[nfiles++];
1361 	}
1362 	rep->lflags = (mode_t)0;
1363 	rep->flinkto = NULL;
1364 	rep->cycle = 0;
1365 	if (argfl || statreq) {
1366 		int doacl;
1367 
1368 		if (lflg)
1369 			doacl = 1;
1370 		else
1371 			doacl = 0;
1372 		if ((*statf)(file, &statb) < 0) {
1373 			if (argfl || errno != ENOENT ||
1374 			    (Lflg && lstat(file, &statb) == 0)) {
1375 				/*
1376 				 * Avoid race between readdir and lstat.
1377 				 * Print error message in case of dangling link.
1378 				 */
1379 				perror(file);
1380 			}
1381 			nfiles--;
1382 			return (NULL);
1383 		}
1384 
1385 		/*
1386 		 * If -H was specified, and the file linked to was
1387 		 * not a directory, then we need to get the info
1388 		 * for the symlink itself.
1389 		 */
1390 		if ((Hflg) && (argfl) &&
1391 		    ((statb.st_mode & S_IFMT) != S_IFDIR)) {
1392 			if (lstat(file, &statb) < 0) {
1393 				perror(file);
1394 			}
1395 		}
1396 
1397 		rep->lnum = statb.st_ino;
1398 		rep->lsize = statb.st_size;
1399 		rep->lblocks = statb.st_blocks;
1400 		switch (statb.st_mode & S_IFMT) {
1401 		case S_IFDIR:
1402 			rep->ltype = 'd';
1403 			if (Rflg) {
1404 				record_ancestry(file, &statb, rep,
1405 				    argfl, myparent);
1406 			}
1407 			break;
1408 		case S_IFBLK:
1409 			rep->ltype = 'b';
1410 			rep->lsize = (off_t)statb.st_rdev;
1411 			break;
1412 		case S_IFCHR:
1413 			rep->ltype = 'c';
1414 			rep->lsize = (off_t)statb.st_rdev;
1415 			break;
1416 		case S_IFIFO:
1417 			rep->ltype = 'p';
1418 			break;
1419 		case S_IFSOCK:
1420 			rep->ltype = 's';
1421 			rep->lsize = 0;
1422 			break;
1423 		case S_IFLNK:
1424 			/* symbolic links may not have ACLs, so elide acl() */
1425 			if ((Lflg == 0) || (Hflg == 0) ||
1426 			    ((Hflg) && (!argfl))) {
1427 				doacl = 0;
1428 			}
1429 			rep->ltype = 'l';
1430 			if (lflg) {
1431 				cc = readlink(file, buf, BUFSIZ);
1432 				if (cc >= 0) {
1433 
1434 					/*
1435 					 * follow the symbolic link
1436 					 * to generate the appropriate
1437 					 * Fflg marker for the object
1438 					 * eg, /bin -> /sym/bin/
1439 					 */
1440 					if ((Fflg || pflg) &&
1441 					    (stat(file, &statb1) >= 0)) {
1442 						switch (statb1.st_mode &
1443 						    S_IFMT) {
1444 						case S_IFDIR:
1445 							buf[cc++] = '/';
1446 							break;
1447 						case S_IFSOCK:
1448 							buf[cc++] = '=';
1449 							break;
1450 						case S_IFDOOR:
1451 							buf[cc++] = '>';
1452 							break;
1453 						case S_IFIFO:
1454 							buf[cc++] = '|';
1455 							break;
1456 						default:
1457 							if ((statb1.st_mode &
1458 							    ~S_IFMT) &
1459 							    (S_IXUSR|S_IXGRP|
1460 							    S_IXOTH))
1461 								buf[cc++] = '*';
1462 							break;
1463 						}
1464 					}
1465 					buf[cc] = '\0';
1466 					rep->flinkto = strdup(buf);
1467 				}
1468 				break;
1469 			}
1470 
1471 			/*
1472 			 * ls /sym behaves differently from ls /sym/
1473 			 * when /sym is a symbolic link. This is fixed
1474 			 * when explicit arguments are specified.
1475 			 */
1476 
1477 #ifdef XPG6
1478 			/* Do not follow a symlink when -F is specified */
1479 			if ((!argfl) || (argfl && Fflg) ||
1480 			    (stat(file, &statb1) < 0))
1481 #else
1482 			/* Follow a symlink when -F is specified */
1483 			if (!argfl || stat(file, &statb1) < 0)
1484 #endif /* XPG6 */
1485 				break;
1486 			if ((statb1.st_mode & S_IFMT) == S_IFDIR) {
1487 				statb = statb1;
1488 				rep->ltype = 'd';
1489 				rep->lsize = statb1.st_size;
1490 				if (Rflg) {
1491 					record_ancestry(file, &statb, rep,
1492 					    argfl, myparent);
1493 				}
1494 			}
1495 			break;
1496 		case S_IFDOOR:
1497 			rep->ltype = 'D';
1498 			break;
1499 		case S_IFREG:
1500 			rep->ltype = '-';
1501 			break;
1502 		case S_IFPORT:
1503 			rep->ltype = 'P';
1504 			break;
1505 		default:
1506 			rep->ltype = '?';
1507 			break;
1508 		}
1509 		rep->lflags = statb.st_mode & ~S_IFMT;
1510 
1511 		if (!S_ISREG(statb.st_mode))
1512 			rep->lflags |= LS_NOTREG;
1513 
1514 		/* ACL: check acl entries count */
1515 		if (doacl) {
1516 
1517 			error = acl_get(file, 0, &rep->aclp);
1518 			if (error) {
1519 				(void) fprintf(stderr,
1520 				    gettext("ls: can't read ACL on %s: %s\n"),
1521 				    file, acl_strerror(error));
1522 				return (NULL);
1523 			}
1524 
1525 			rep->acl = ' ';
1526 
1527 			if (rep->aclp &&
1528 			    ((acl_flags(rep->aclp) & ACL_IS_TRIVIAL) == 0)) {
1529 				rep->acl = '+';
1530 				/*
1531 				 * Special handling for ufs aka aclent_t ACL's
1532 				 */
1533 				if (acl_type(rep->aclp) == ACLENT_T) {
1534 					/*
1535 					 * For files with non-trivial acls, the
1536 					 * effective group permissions are the
1537 					 * intersection of the GROUP_OBJ value
1538 					 * and the CLASS_OBJ (acl mask) value.
1539 					 * Determine both the GROUP_OBJ and
1540 					 * CLASS_OBJ for this file and insert
1541 					 * the logical AND of those two values
1542 					 * in the group permissions field
1543 					 * of the lflags value for this file.
1544 					 */
1545 
1546 					/*
1547 					 * Until found in acl list, assume
1548 					 * maximum permissions for both group
1549 					 * a nd mask.  (Just in case the acl
1550 					 * lacks either value for some reason.)
1551 					 */
1552 					groupperm = 07;
1553 					mask = 07;
1554 					grouppermfound = 0;
1555 					maskfound = 0;
1556 					aclcnt = acl_cnt(rep->aclp);
1557 					for (tp =
1558 					    (aclent_t *)acl_data(rep->aclp);
1559 					    aclcnt--; tp++) {
1560 						if (tp->a_type == GROUP_OBJ) {
1561 							groupperm = tp->a_perm;
1562 							grouppermfound = 1;
1563 							continue;
1564 						}
1565 						if (tp->a_type == CLASS_OBJ) {
1566 							mask = tp->a_perm;
1567 							maskfound = 1;
1568 						}
1569 						if (grouppermfound && maskfound)
1570 							break;
1571 					}
1572 
1573 
1574 					/* reset all the group bits */
1575 					rep->lflags &= ~S_IRWXG;
1576 
1577 					/*
1578 					 * Now set them to the logical AND of
1579 					 * the GROUP_OBJ permissions and the
1580 					 * acl mask.
1581 					 */
1582 
1583 					rep->lflags |= (groupperm & mask) << 3;
1584 
1585 				} else if (acl_type(rep->aclp) == ACE_T) {
1586 					int mode;
1587 					mode = grp_mask_to_mode(rep->aclp);
1588 					rep->lflags &= ~S_IRWXG;
1589 					rep->lflags |= mode;
1590 				}
1591 			}
1592 
1593 			if (!vflg && !Vflg && rep->aclp) {
1594 				acl_free(rep->aclp);
1595 				rep->aclp = NULL;
1596 			}
1597 
1598 			if (atflg && pathconf(file, _PC_XATTR_EXISTS) == 1)
1599 				rep->acl = '@';
1600 
1601 		} else
1602 			rep->acl = ' ';
1603 
1604 		/* mask ISARG and other file-type bits */
1605 
1606 		rep->luid = statb.st_uid;
1607 		rep->lgid = statb.st_gid;
1608 		rep->lnl = statb.st_nlink;
1609 		if (uflg || (tmflg && atm))
1610 			rep->lmtime = statb.st_atim;
1611 		else if (cflg || (tmflg && ctm))
1612 			rep->lmtime = statb.st_ctim;
1613 		else
1614 			rep->lmtime = statb.st_mtim;
1615 		rep->lat = statb.st_atim;
1616 		rep->lct = statb.st_ctim;
1617 		rep->lmt = statb.st_mtim;
1618 
1619 		if (rep->ltype != 'b' && rep->ltype != 'c')
1620 			tblocks += rep->lblocks;
1621 
1622 		/* Get extended system attributes */
1623 
1624 		rep->exttr = NULL;
1625 		rep->extm = NULL;
1626 		if ((saflg || (tmflg && crtm) || (tmflg && alltm)) &&
1627 		    (sysattr_support(file, _PC_SATTR_EXISTS) == 1)) {
1628 			int i;
1629 
1630 			sacnt = attr_count();
1631 			/*
1632 			 * Allocate 'sacnt' size array to hold extended
1633 			 * system attribute name (verbose) or respective
1634 			 * symbol represenation (compact).
1635 			 */
1636 			rep->exttr = xmalloc(sacnt * sizeof (struct attrb),
1637 			    rep);
1638 
1639 			/* initialize boolean attribute list */
1640 			for (i = 0; i < sacnt; i++)
1641 				rep->exttr[i].name = NULL;
1642 			if (get_sysxattr(file, rep) != 0) {
1643 				(void) fprintf(stderr,
1644 				    gettext("ls:Failed to retrieve "
1645 				    "extended system attribute from "
1646 				    "%s\n"), file);
1647 				rep->exttr[0].name = xmalloc(2, rep);
1648 				(void) strlcpy(rep->exttr[0].name, "?", 2);
1649 			}
1650 		}
1651 	}
1652 	return (rep);
1653 }
1654 
1655 /*
1656  * returns pathname of the form dir/file;
1657  * dir and file are null-terminated strings.
1658  */
1659 static char *
1660 makename(char *dir, char *file)
1661 {
1662 	/*
1663 	 * PATH_MAX is the maximum length of a path name.
1664 	 * MAXNAMLEN is the maximum length of any path name component.
1665 	 * Allocate space for both, plus the '/' in the middle
1666 	 * and the null character at the end.
1667 	 * dfile is static as this is returned by makename().
1668 	 */
1669 	static char dfile[PATH_MAX + 1 + MAXNAMLEN + 1];
1670 	char *dp, *fp;
1671 
1672 	dp = dfile;
1673 	fp = dir;
1674 	while (*fp)
1675 		*dp++ = *fp++;
1676 	if (dp > dfile && *(dp - 1) != '/')
1677 		*dp++ = '/';
1678 	fp = file;
1679 	while (*fp)
1680 		*dp++ = *fp++;
1681 	*dp = '\0';
1682 	return (dfile);
1683 }
1684 
1685 
1686 #include <pwd.h>
1687 #include <grp.h>
1688 #include <utmpx.h>
1689 
1690 struct	utmpx utmp;
1691 
1692 #define	NMAX	(sizeof (utmp.ut_name))
1693 #define	SCPYN(a, b)	(void) strncpy(a, b, NMAX)
1694 
1695 
1696 struct cachenode {		/* this struct must be zeroed before using */
1697 	struct cachenode *lesschild;	/* subtree whose entries < val */
1698 	struct cachenode *grtrchild;	/* subtree whose entries > val */
1699 	long val;			/* the uid or gid of this entry */
1700 	int initted;			/* name has been filled in */
1701 	char name[NMAX+1];		/* the string that val maps to */
1702 };
1703 static struct cachenode *names, *groups;
1704 
1705 static struct cachenode *
1706 findincache(struct cachenode **head, long val)
1707 {
1708 	struct cachenode **parent = head;
1709 	struct cachenode *c = *parent;
1710 
1711 	while (c != NULL) {
1712 		if (val == c->val) {
1713 			/* found it */
1714 			return (c);
1715 		} else if (val < c->val) {
1716 			parent = &c->lesschild;
1717 			c = c->lesschild;
1718 		} else {
1719 			parent = &c->grtrchild;
1720 			c = c->grtrchild;
1721 		}
1722 	}
1723 
1724 	/* not in the cache, make a new entry for it */
1725 	c = calloc(1, sizeof (struct cachenode));
1726 	if (c == NULL) {
1727 		perror("ls");
1728 		exit(2);
1729 	}
1730 	*parent = c;
1731 	c->val = val;
1732 	return (c);
1733 }
1734 
1735 /*
1736  * get name from cache, or passwd file for a given uid;
1737  * lastuid is set to uid.
1738  */
1739 static char *
1740 getname(uid_t uid)
1741 {
1742 	struct passwd *pwent;
1743 	struct cachenode *c;
1744 
1745 	if ((uid == lastuid) && lastuname)
1746 		return (lastuname);
1747 
1748 	c = findincache(&names, uid);
1749 	if (c->initted == 0) {
1750 		if ((pwent = getpwuid(uid)) != NULL) {
1751 			SCPYN(&c->name[0], pwent->pw_name);
1752 		} else {
1753 			(void) sprintf(&c->name[0], "%-8u", (int)uid);
1754 		}
1755 		c->initted = 1;
1756 	}
1757 	lastuid = uid;
1758 	lastuname = &c->name[0];
1759 	return (lastuname);
1760 }
1761 
1762 /*
1763  * get name from cache, or group file for a given gid;
1764  * lastgid is set to gid.
1765  */
1766 static char *
1767 getgroup(gid_t gid)
1768 {
1769 	struct group *grent;
1770 	struct cachenode *c;
1771 
1772 	if ((gid == lastgid) && lastgname)
1773 		return (lastgname);
1774 
1775 	c = findincache(&groups, gid);
1776 	if (c->initted == 0) {
1777 		if ((grent = getgrgid(gid)) != NULL) {
1778 			SCPYN(&c->name[0], grent->gr_name);
1779 		} else {
1780 			(void) sprintf(&c->name[0], "%-8u", (int)gid);
1781 		}
1782 		c->initted = 1;
1783 	}
1784 	lastgid = gid;
1785 	lastgname = &c->name[0];
1786 	return (lastgname);
1787 }
1788 
1789 /* return >0 if item pointed by pp2 should appear first */
1790 static int
1791 compar(struct lbuf **pp1, struct lbuf **pp2)
1792 {
1793 	struct lbuf *p1, *p2;
1794 
1795 	p1 = *pp1;
1796 	p2 = *pp2;
1797 	if (dflg == 0) {
1798 /*
1799  * compare two names in ls-command one of which is file
1800  * and the other is a directory;
1801  * this portion is not used for comparing files within
1802  * a directory name of ls-command;
1803  */
1804 		if (p1->lflags&ISARG && p1->ltype == 'd') {
1805 			if (!(p2->lflags&ISARG && p2->ltype == 'd'))
1806 				return (1);
1807 		} else {
1808 			if (p2->lflags&ISARG && p2->ltype == 'd')
1809 				return (-1);
1810 		}
1811 	}
1812 	if (tflg) {
1813 		if (p2->lmtime.tv_sec > p1->lmtime.tv_sec)
1814 			return (rflg);
1815 		else if (p2->lmtime.tv_sec < p1->lmtime.tv_sec)
1816 			return (-rflg);
1817 		/* times are equal to the sec, check nsec */
1818 		if (p2->lmtime.tv_nsec > p1->lmtime.tv_nsec)
1819 			return (rflg);
1820 		else if (p2->lmtime.tv_nsec < p1->lmtime.tv_nsec)
1821 			return (-rflg);
1822 		/* if times are equal, fall through and sort by name */
1823 	} else if (Sflg) {
1824 		/*
1825 		 * The size stored in lsize can be either the
1826 		 * size or the major minor number (in the case of
1827 		 * block and character special devices).  If it's
1828 		 * a major minor number, then the size is considered
1829 		 * to be zero and we want to fall through and sort
1830 		 * by name.  In addition, if the size of p2 is equal
1831 		 * to the size of p1 we want to fall through and
1832 		 * sort by name.
1833 		 */
1834 		off_t	p1size = (p1->ltype == 'b') ||
1835 		    (p1->ltype == 'c') ? 0 : p1->lsize;
1836 		off_t	p2size = (p2->ltype == 'b') ||
1837 		    (p2->ltype == 'c') ? 0 : p2->lsize;
1838 		if (p2size > p1size) {
1839 			return (rflg);
1840 		} else if (p2size < p1size) {
1841 			return (-rflg);
1842 		}
1843 		/* Sizes are equal, fall through and sort by name. */
1844 	}
1845 	return (rflg * strcoll(
1846 	    p1->lflags & ISARG ? p1->ln.namep : p1->ln.lname,
1847 	    p2->lflags&ISARG ? p2->ln.namep : p2->ln.lname));
1848 }
1849 
1850 static void
1851 pprintf(char *s1, char *s2)
1852 {
1853 	csi_pprintf((unsigned char *)s1);
1854 	csi_pprintf((unsigned char *)s2);
1855 }
1856 
1857 static void
1858 csi_pprintf(unsigned char *s)
1859 {
1860 	unsigned char *cp;
1861 	char	c;
1862 	int	i;
1863 	int	c_len;
1864 	int	p_col;
1865 	wchar_t	pcode;
1866 
1867 	if (!qflg && !bflg) {
1868 		for (cp = s; *cp != '\0'; cp++) {
1869 			(void) putchar(*cp);
1870 			curcol++;
1871 		}
1872 		return;
1873 	}
1874 
1875 	for (cp = s; *cp; ) {
1876 		if (isascii(c = *cp)) {
1877 			if (!isprint(c)) {
1878 				if (qflg) {
1879 					c = '?';
1880 				} else {
1881 					curcol += 3;
1882 					(void) putc('\\', stdout);
1883 					c = '0' + ((*cp >> 6) & 07);
1884 					(void) putc(c, stdout);
1885 					c = '0' + ((*cp >> 3) & 07);
1886 					(void) putc(c, stdout);
1887 					c = '0' + (*cp & 07);
1888 				}
1889 			}
1890 			curcol++;
1891 			cp++;
1892 			(void) putc(c, stdout);
1893 			continue;
1894 		}
1895 
1896 		if ((c_len = mbtowc(&pcode, (char *)cp, MB_LEN_MAX)) <= 0) {
1897 			c_len = 1;
1898 			goto not_print;
1899 		}
1900 
1901 		if ((p_col = wcwidth(pcode)) > 0) {
1902 			(void) putwchar(pcode);
1903 			cp += c_len;
1904 			curcol += p_col;
1905 			continue;
1906 		}
1907 
1908 not_print:
1909 		for (i = 0; i < c_len; i++) {
1910 			if (qflg) {
1911 				c = '?';
1912 			} else {
1913 				curcol += 3;
1914 				(void) putc('\\', stdout);
1915 				c = '0' + ((*cp >> 6) & 07);
1916 				(void) putc(c, stdout);
1917 				c = '0' + ((*cp >> 3) & 07);
1918 				(void) putc(c, stdout);
1919 				c = '0' + (*cp & 07);
1920 			}
1921 			curcol++;
1922 			(void) putc(c, stdout);
1923 			cp++;
1924 		}
1925 	}
1926 }
1927 
1928 static int
1929 strcol(unsigned char *s1)
1930 {
1931 	int	w;
1932 	int	w_col;
1933 	int	len;
1934 	wchar_t	wc;
1935 
1936 	w = 0;
1937 	while (*s1) {
1938 		if (isascii(*s1)) {
1939 			w++;
1940 			s1++;
1941 			continue;
1942 		}
1943 
1944 		if ((len = mbtowc(&wc, (char *)s1, MB_LEN_MAX)) <= 0) {
1945 			w++;
1946 			s1++;
1947 			continue;
1948 		}
1949 
1950 		if ((w_col = wcwidth(wc)) < 0)
1951 			w_col = len;
1952 		s1 += len;
1953 		w += w_col;
1954 	}
1955 	return (w);
1956 }
1957 
1958 /*
1959  * Convert an unsigned long long to a string representation and place the
1960  * result in the caller-supplied buffer.
1961  *
1962  * The number provided is a size in bytes.  The number is first
1963  * converted to an integral multiple of 'scale' bytes.  This new
1964  * number is then scaled down until it is small enough to be in a good
1965  * human readable format, i.e.  in the range 0 thru scale-1.  If the
1966  * number used to derive the final number is not a multiple of scale, and
1967  * the final number has only a single significant digit, we compute
1968  * tenths of units to provide a second significant digit.
1969  *
1970  * The value "(unsigned long long)-1" is a special case and is always
1971  * converted to "-1".
1972  *
1973  * A pointer to the caller-supplied buffer is returned.
1974  */
1975 static char *
1976 number_to_scaled_string(
1977 			numbuf_t buf,		/* put the result here */
1978 			unsigned long long number, /* convert this number */
1979 			long scale)
1980 {
1981 	unsigned long long save;
1982 	/* Measurement: kilo, mega, giga, tera, peta, exa */
1983 	char *uom = "KMGTPE";
1984 
1985 	if ((long long)number == (long long)-1) {
1986 		(void) strlcpy(buf, "-1", sizeof (numbuf_t));
1987 		return (buf);
1988 	}
1989 
1990 	save = number;
1991 	number = number / scale;
1992 
1993 	/*
1994 	 * Now we have number as a count of scale units.
1995 	 * If no further scaling is necessary, we round up as appropriate.
1996 	 *
1997 	 * The largest value number could have had entering the routine is
1998 	 * 16 Exabytes, so running off the end of the uom array should
1999 	 * never happen.  We check for that, though, as a guard against
2000 	 * a breakdown elsewhere in the algorithm.
2001 	 */
2002 	if (number < (unsigned long long)scale) {
2003 		if ((save % scale) >= (unsigned long long)(scale / 2)) {
2004 			if (++number == (unsigned long long)scale) {
2005 				uom++;
2006 				number = 1;
2007 			}
2008 		}
2009 	} else {
2010 		while ((number >= (unsigned long long)scale) && (*uom != 'E')) {
2011 			uom++; /* next unit of measurement */
2012 			save = number;
2013 			/*
2014 			 * If we're over half way to the next unit of
2015 			 * 'scale' bytes (which means we should round
2016 			 * up), then adding half of 'scale' prior to
2017 			 * the division will push us into that next
2018 			 * unit of scale when we perform the division
2019 			 */
2020 			number = (number + (scale / 2)) / scale;
2021 		}
2022 	}
2023 
2024 	/* check if we should output a decimal place after the point */
2025 	if ((save / scale) < 10) {
2026 		/* snprintf() will round for us */
2027 		float fnum = (float)save / scale;
2028 		(void) snprintf(buf, sizeof (numbuf_t), "%2.1f%c",
2029 		    fnum, *uom);
2030 	} else {
2031 		(void) snprintf(buf, sizeof (numbuf_t), "%4llu%c",
2032 		    number, *uom);
2033 	}
2034 	return (buf);
2035 }
2036 
2037 /* Get extended system attributes and set the display */
2038 
2039 int
2040 get_sysxattr(char *fname, struct lbuf *rep)
2041 {
2042 	boolean_t	value;
2043 	data_type_t	type;
2044 	int		error;
2045 	char		*name;
2046 	int		i;
2047 
2048 	if ((error = getattrat(AT_FDCWD, XATTR_VIEW_READWRITE, fname,
2049 	    &response)) != 0) {
2050 		perror("ls:getattrat");
2051 		return (error);
2052 	}
2053 
2054 	/*
2055 	 * Allocate 'sacnt' size array to hold extended timestamp
2056 	 * system attributes and initialize the array.
2057 	 */
2058 	rep->extm = xmalloc(sacnt * sizeof (struct attrtm), rep);
2059 	for (i = 0; i < sacnt; i++) {
2060 		rep->extm[i].stm = 0;
2061 		rep->extm[i].nstm = 0;
2062 		rep->extm[i].name = NULL;
2063 	}
2064 	while ((pair = nvlist_next_nvpair(response, pair)) != NULL) {
2065 		name = nvpair_name(pair);
2066 		type = nvpair_type(pair);
2067 		if (type == DATA_TYPE_BOOLEAN_VALUE) {
2068 			error = nvpair_value_boolean_value(pair, &value);
2069 			if (error) {
2070 				(void) fprintf(stderr,
2071 				    gettext("nvpair_value_boolean_value "
2072 				    "failed: error = %d\n"), error);
2073 				continue;
2074 			}
2075 			if (name != NULL)
2076 				set_sysattrb_display(name, value, rep);
2077 			continue;
2078 		} else if (type == DATA_TYPE_UINT64_ARRAY) {
2079 			if (name != NULL)
2080 				set_sysattrtm_display(name, rep);
2081 			continue;
2082 		}
2083 	}
2084 	nvlist_free(response);
2085 	return (0);
2086 }
2087 
2088 /* Set extended system attribute boolean display */
2089 
2090 void
2091 set_sysattrb_display(char *name, boolean_t val, struct lbuf *rep)
2092 {
2093 	f_attr_t	fattr;
2094 	const char	*opt;
2095 	size_t		len;
2096 
2097 	fattr = name_to_attr(name);
2098 	if (fattr != F_ATTR_INVAL && fattr < sacnt) {
2099 		if (vopt) {
2100 			len = strlen(name);
2101 			if (val) {
2102 				rep->exttr[fattr].name = xmalloc(len + 1, rep);
2103 				(void) strlcpy(rep->exttr[fattr].name, name,
2104 				    len + 1);
2105 			} else {
2106 				rep->exttr[fattr].name = xmalloc(len + 3, rep);
2107 				(void) snprintf(rep->exttr[fattr].name, len + 3,
2108 				    "no%s", name);
2109 			}
2110 		} else {
2111 			opt = attr_to_option(fattr);
2112 			if (opt != NULL) {
2113 				len = strlen(opt);
2114 				rep->exttr[fattr].name = xmalloc(len + 1, rep);
2115 				if (val)
2116 					(void) strlcpy(rep->exttr[fattr].name,
2117 					    opt, len + 1);
2118 				else
2119 					(void) strlcpy(rep->exttr[fattr].name,
2120 					    "-", len + 1);
2121 			}
2122 		}
2123 	}
2124 }
2125 
2126 /* Set extended system attribute timestamp display */
2127 
2128 void
2129 set_sysattrtm_display(char *name, struct lbuf *rep)
2130 {
2131 	uint_t		nelem;
2132 	uint64_t	*value;
2133 	int		i;
2134 	size_t		len;
2135 
2136 	if (nvpair_value_uint64_array(pair, &value, &nelem) == 0) {
2137 		if (*value != NULL) {
2138 			len = strlen(name);
2139 			i = 0;
2140 			while (rep->extm[i].stm != 0 && i < sacnt)
2141 				i++;
2142 			rep->extm[i].stm = value[0];
2143 			rep->extm[i].nstm = value[1];
2144 			rep->extm[i].name = xmalloc(len + 1, rep);
2145 			(void) strlcpy(rep->extm[i].name, name, len + 1);
2146 		}
2147 	}
2148 }
2149 
2150 void
2151 format_time(const char *format, time_t sec)
2152 {
2153 
2154 	(void) strftime(time_buf, sizeof (time_buf),
2155 	    dcgettext(NULL, format, LC_TIME),
2156 	    localtime(&sec));
2157 }
2158 
2159 void
2160 format_etime(const char *format, time_t sec, time_t nsec)
2161 {
2162 	char fmt_buf[FMTSIZE];
2163 
2164 	(void) snprintf(fmt_buf, FMTSIZE,
2165 	    format, nsec);
2166 	(void) strftime(time_buf, sizeof (time_buf),
2167 	    fmt_buf, localtime(&sec));
2168 }
2169 
2170 /* Format timestamp extended system attributes */
2171 
2172 void
2173 format_attrtime(struct lbuf *p)
2174 {
2175 	int	tmattr = 0;
2176 	int i;
2177 
2178 	if (p->extm != NULL) {
2179 		for (i = 0; i < sacnt; i++) {
2180 			if (p->extm[i].name != NULL) {
2181 				tmattr = 1;
2182 				break;
2183 			}
2184 		}
2185 	}
2186 	if (tmattr) {
2187 		if (Eflg)
2188 			format_etime(FORMAT4, (time_t)p->extm[i].stm,
2189 			    (time_t)p->extm[i].nstm);
2190 		else  {
2191 			if ((p->lmtime.tv_sec < year) ||
2192 			    (p->lmtime.tv_sec > now))
2193 				format_time(FORMAT1,
2194 				    (time_t)p->extm[i].stm);
2195 			else
2196 				format_time(FORMAT2,
2197 				    (time_t)p->extm[i].stm);
2198 		}
2199 	}
2200 }
2201 
2202 void
2203 print_time(struct lbuf *p)
2204 {
2205 	int i = 0;
2206 
2207 	new_line();
2208 	if (Eflg) {
2209 		format_etime(FORMAT4, p->lat.tv_sec, p->lat.tv_nsec);
2210 		(void) printf("		timestamp: atime	%s\n",
2211 		    time_buf);
2212 		format_etime(FORMAT4, p->lct.tv_sec, p->lct.tv_nsec);
2213 		(void) printf("		timestamp: ctime	%s\n",
2214 		    time_buf);
2215 		format_etime(FORMAT4, p->lmt.tv_sec, p->lmt.tv_nsec);
2216 		(void) printf("		timestamp: mtime	%s\n",
2217 		    time_buf);
2218 		if (p->extm != NULL) {
2219 			while (p->extm[i].nstm != 0 && i < sacnt) {
2220 				format_etime(FORMAT4, p->extm[i].stm,
2221 				    p->extm[i].nstm);
2222 				if (p->extm[i].name != NULL) {
2223 					(void) printf("		timestamp:"
2224 					    " %s	%s\n",
2225 					    p->extm[i].name, time_buf);
2226 				}
2227 				i++;
2228 			}
2229 		}
2230 	} else {
2231 		format_time(FORMAT3, p->lat.tv_sec);
2232 		(void) printf("		timestamp: atime	%s\n",
2233 		    time_buf);
2234 		format_time(FORMAT3, p->lct.tv_sec);
2235 		(void) printf("		timestamp: ctime	%s\n",
2236 		    time_buf);
2237 		format_time(FORMAT3, p->lmt.tv_sec);
2238 		(void) printf("		timestamp: mtime	%s\n",
2239 		    time_buf);
2240 		if (p->extm != NULL) {
2241 			while (p->extm[i].stm != 0 && i < sacnt) {
2242 				format_time(FORMAT3, p->extm[i].stm);
2243 				if (p->extm[i].name != NULL) {
2244 					(void) printf("		timestamp:"
2245 					    " %s	%s\n",
2246 					    p->extm[i].name, time_buf);
2247 				}
2248 				i++;
2249 			}
2250 		}
2251 	}
2252 }
2253 
2254 /* Free extended system attribute lists */
2255 
2256 void
2257 free_sysattr(struct lbuf *p)
2258 {
2259 	int i;
2260 
2261 	if (p->exttr != NULL) {
2262 		for (i = 0; i < sacnt; i++) {
2263 			if (p->exttr[i].name != NULL)
2264 				free(p->exttr[i].name);
2265 		}
2266 		free(p->exttr);
2267 	}
2268 	if (p->extm != NULL) {
2269 		for (i = 0; i < sacnt; i++) {
2270 			if (p->extm[i].name != NULL)
2271 				free(p->extm[i].name);
2272 		}
2273 		free(p->extm);
2274 	}
2275 }
2276 
2277 /* Allocate extended system attribute list */
2278 
2279 void *
2280 xmalloc(size_t size, struct lbuf *p)
2281 {
2282 	if ((p = malloc(size)) == NULL) {
2283 		perror("ls");
2284 		free_sysattr(p);
2285 		nvlist_free(response);
2286 		exit(2);
2287 	}
2288 	return (p);
2289 }
2290