xref: /titanic_52/usr/src/cmd/ls/ls.c (revision 6029a2d88c01674debfd7c2e16c941a97302b739)
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 user 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 
1265 #define	OWNED_GROUP	(ACE_GROUP | ACE_IDENTIFIER_GROUP)
1266 #define	IS_TYPE_ALLOWED(type)	((type) == ACE_ACCESS_ALLOWED_ACE_TYPE)
1267 
1268 int
1269 grp_mask_to_mode(acl_t *acep)
1270 {
1271 	int mode = 0, seen = 0;
1272 	int acecnt;
1273 	int flags;
1274 	ace_t *ap;
1275 
1276 	acecnt = acl_cnt(acep);
1277 	for (ap = (ace_t *)acl_data(acep); acecnt--; ap++) {
1278 
1279 		if (ap->a_type != ACE_ACCESS_ALLOWED_ACE_TYPE &&
1280 		    ap->a_type != ACE_ACCESS_DENIED_ACE_TYPE)
1281 			continue;
1282 
1283 		if (ap->a_flags & ACE_INHERIT_ONLY_ACE)
1284 			continue;
1285 
1286 		/*
1287 		 * if it is first group@ or first everyone@
1288 		 * for each of read, write and execute, then
1289 		 * that will be the group mode bit.
1290 		 */
1291 		flags = ap->a_flags & ACE_TYPE_FLAGS;
1292 		if (flags == OWNED_GROUP || flags == ACE_EVERYONE) {
1293 			if (ap->a_access_mask & ACE_READ_DATA) {
1294 				if (!(seen & S_IRGRP)) {
1295 					seen |= S_IRGRP;
1296 					if (IS_TYPE_ALLOWED(ap->a_type))
1297 						mode |= S_IRGRP;
1298 				}
1299 			}
1300 			if (ap->a_access_mask & ACE_WRITE_DATA) {
1301 				if (!(seen & S_IWGRP)) {
1302 					seen |= S_IWGRP;
1303 					if (IS_TYPE_ALLOWED(ap->a_type))
1304 						mode |= S_IWGRP;
1305 				}
1306 			}
1307 			if (ap->a_access_mask & ACE_EXECUTE) {
1308 				if (!(seen & S_IXGRP)) {
1309 					seen |= S_IXGRP;
1310 					if (IS_TYPE_ALLOWED(ap->a_type))
1311 						mode |= S_IXGRP;
1312 				}
1313 			}
1314 		}
1315 	}
1316 	return (mode);
1317 }
1318 
1319 /*
1320  * get status of file and recomputes tblocks;
1321  * argfl = 1 if file is a name in ls-command and = 0
1322  * for filename in a directory whose name is an
1323  * argument in the command;
1324  * stores a pointer in flist[nfiles] and
1325  * returns that pointer;
1326  * returns NULL if failed;
1327  */
1328 static struct lbuf *
1329 gstat(char *file, int argfl, struct ditem *myparent)
1330 {
1331 	struct stat statb, statb1;
1332 	struct lbuf *rep;
1333 	char buf[BUFSIZ];
1334 	ssize_t cc;
1335 	int (*statf)() = ((Lflg) || (Hflg && argfl)) ? stat : lstat;
1336 	int aclcnt;
1337 	int error;
1338 	aclent_t *tp;
1339 	o_mode_t groupperm, mask;
1340 	int grouppermfound, maskfound;
1341 
1342 	if (nomocore)
1343 		return (NULL);
1344 
1345 	if (nfiles >= maxfils) {
1346 		/*
1347 		 * all flist/lbuf pair assigned files, time to get some
1348 		 * more space
1349 		 */
1350 		maxfils += quantn;
1351 		if (((flist = realloc(flist,
1352 		    maxfils * sizeof (struct lbuf *))) == NULL) ||
1353 		    ((nxtlbf = malloc(quantn *
1354 		    sizeof (struct lbuf))) == NULL)) {
1355 			perror("ls");
1356 			nomocore = 1;
1357 			return (NULL);
1358 		}
1359 	}
1360 
1361 	/*
1362 	 * nfiles is reset to nargs for each directory
1363 	 * that is given as an argument maxn is checked
1364 	 * to prevent the assignment of an lbuf to a flist entry
1365 	 * that already has one assigned.
1366 	 */
1367 	if (nfiles >= maxn) {
1368 		rep = nxtlbf++;
1369 		flist[nfiles++] = rep;
1370 		maxn = nfiles;
1371 	} else {
1372 		rep = flist[nfiles++];
1373 	}
1374 	rep->lflags = (mode_t)0;
1375 	rep->flinkto = NULL;
1376 	rep->cycle = 0;
1377 	if (argfl || statreq) {
1378 		int doacl;
1379 
1380 		if (lflg)
1381 			doacl = 1;
1382 		else
1383 			doacl = 0;
1384 		if ((*statf)(file, &statb) < 0) {
1385 			if (argfl || errno != ENOENT ||
1386 			    (Lflg && lstat(file, &statb) == 0)) {
1387 				/*
1388 				 * Avoid race between readdir and lstat.
1389 				 * Print error message in case of dangling link.
1390 				 */
1391 				perror(file);
1392 			}
1393 			nfiles--;
1394 			return (NULL);
1395 		}
1396 
1397 		/*
1398 		 * If -H was specified, and the file linked to was
1399 		 * not a directory, then we need to get the info
1400 		 * for the symlink itself.
1401 		 */
1402 		if ((Hflg) && (argfl) &&
1403 		    ((statb.st_mode & S_IFMT) != S_IFDIR)) {
1404 			if (lstat(file, &statb) < 0) {
1405 				perror(file);
1406 			}
1407 		}
1408 
1409 		rep->lnum = statb.st_ino;
1410 		rep->lsize = statb.st_size;
1411 		rep->lblocks = statb.st_blocks;
1412 		switch (statb.st_mode & S_IFMT) {
1413 		case S_IFDIR:
1414 			rep->ltype = 'd';
1415 			if (Rflg) {
1416 				record_ancestry(file, &statb, rep,
1417 				    argfl, myparent);
1418 			}
1419 			break;
1420 		case S_IFBLK:
1421 			rep->ltype = 'b';
1422 			rep->lsize = (off_t)statb.st_rdev;
1423 			break;
1424 		case S_IFCHR:
1425 			rep->ltype = 'c';
1426 			rep->lsize = (off_t)statb.st_rdev;
1427 			break;
1428 		case S_IFIFO:
1429 			rep->ltype = 'p';
1430 			break;
1431 		case S_IFSOCK:
1432 			rep->ltype = 's';
1433 			rep->lsize = 0;
1434 			break;
1435 		case S_IFLNK:
1436 			/* symbolic links may not have ACLs, so elide acl() */
1437 			if ((Lflg == 0) || (Hflg == 0) ||
1438 			    ((Hflg) && (!argfl))) {
1439 				doacl = 0;
1440 			}
1441 			rep->ltype = 'l';
1442 			if (lflg) {
1443 				cc = readlink(file, buf, BUFSIZ);
1444 				if (cc >= 0) {
1445 
1446 					/*
1447 					 * follow the symbolic link
1448 					 * to generate the appropriate
1449 					 * Fflg marker for the object
1450 					 * eg, /bin -> /sym/bin/
1451 					 */
1452 					if ((Fflg || pflg) &&
1453 					    (stat(file, &statb1) >= 0)) {
1454 						switch (statb1.st_mode &
1455 						    S_IFMT) {
1456 						case S_IFDIR:
1457 							buf[cc++] = '/';
1458 							break;
1459 						case S_IFSOCK:
1460 							buf[cc++] = '=';
1461 							break;
1462 						case S_IFDOOR:
1463 							buf[cc++] = '>';
1464 							break;
1465 						case S_IFIFO:
1466 							buf[cc++] = '|';
1467 							break;
1468 						default:
1469 							if ((statb1.st_mode &
1470 							    ~S_IFMT) &
1471 							    (S_IXUSR|S_IXGRP|
1472 							    S_IXOTH))
1473 								buf[cc++] = '*';
1474 							break;
1475 						}
1476 					}
1477 					buf[cc] = '\0';
1478 					rep->flinkto = strdup(buf);
1479 				}
1480 				break;
1481 			}
1482 
1483 			/*
1484 			 * ls /sym behaves differently from ls /sym/
1485 			 * when /sym is a symbolic link. This is fixed
1486 			 * when explicit arguments are specified.
1487 			 */
1488 
1489 #ifdef XPG6
1490 			/* Do not follow a symlink when -F is specified */
1491 			if ((!argfl) || (argfl && Fflg) ||
1492 			    (stat(file, &statb1) < 0))
1493 #else
1494 			/* Follow a symlink when -F is specified */
1495 			if (!argfl || stat(file, &statb1) < 0)
1496 #endif /* XPG6 */
1497 				break;
1498 			if ((statb1.st_mode & S_IFMT) == S_IFDIR) {
1499 				statb = statb1;
1500 				rep->ltype = 'd';
1501 				rep->lsize = statb1.st_size;
1502 				if (Rflg) {
1503 					record_ancestry(file, &statb, rep,
1504 					    argfl, myparent);
1505 				}
1506 			}
1507 			break;
1508 		case S_IFDOOR:
1509 			rep->ltype = 'D';
1510 			break;
1511 		case S_IFREG:
1512 			rep->ltype = '-';
1513 			break;
1514 		case S_IFPORT:
1515 			rep->ltype = 'P';
1516 			break;
1517 		default:
1518 			rep->ltype = '?';
1519 			break;
1520 		}
1521 		rep->lflags = statb.st_mode & ~S_IFMT;
1522 
1523 		if (!S_ISREG(statb.st_mode))
1524 			rep->lflags |= LS_NOTREG;
1525 
1526 		/* ACL: check acl entries count */
1527 		if (doacl) {
1528 
1529 			error = acl_get(file, 0, &rep->aclp);
1530 			if (error) {
1531 				(void) fprintf(stderr,
1532 				    gettext("ls: can't read ACL on %s: %s\n"),
1533 				    file, acl_strerror(error));
1534 				return (NULL);
1535 			}
1536 
1537 			rep->acl = ' ';
1538 
1539 			if (rep->aclp &&
1540 			    ((acl_flags(rep->aclp) & ACL_IS_TRIVIAL) == 0)) {
1541 				rep->acl = '+';
1542 				/*
1543 				 * Special handling for ufs aka aclent_t ACL's
1544 				 */
1545 				if (acl_type(rep->aclp) == ACLENT_T) {
1546 					/*
1547 					 * For files with non-trivial acls, the
1548 					 * effective group permissions are the
1549 					 * intersection of the GROUP_OBJ value
1550 					 * and the CLASS_OBJ (acl mask) value.
1551 					 * Determine both the GROUP_OBJ and
1552 					 * CLASS_OBJ for this file and insert
1553 					 * the logical AND of those two values
1554 					 * in the group permissions field
1555 					 * of the lflags value for this file.
1556 					 */
1557 
1558 					/*
1559 					 * Until found in acl list, assume
1560 					 * maximum permissions for both group
1561 					 * a nd mask.  (Just in case the acl
1562 					 * lacks either value for some reason.)
1563 					 */
1564 					groupperm = 07;
1565 					mask = 07;
1566 					grouppermfound = 0;
1567 					maskfound = 0;
1568 					aclcnt = acl_cnt(rep->aclp);
1569 					for (tp =
1570 					    (aclent_t *)acl_data(rep->aclp);
1571 					    aclcnt--; tp++) {
1572 						if (tp->a_type == GROUP_OBJ) {
1573 							groupperm = tp->a_perm;
1574 							grouppermfound = 1;
1575 							continue;
1576 						}
1577 						if (tp->a_type == CLASS_OBJ) {
1578 							mask = tp->a_perm;
1579 							maskfound = 1;
1580 						}
1581 						if (grouppermfound && maskfound)
1582 							break;
1583 					}
1584 
1585 
1586 					/* reset all the group bits */
1587 					rep->lflags &= ~S_IRWXG;
1588 
1589 					/*
1590 					 * Now set them to the logical AND of
1591 					 * the GROUP_OBJ permissions and the
1592 					 * acl mask.
1593 					 */
1594 
1595 					rep->lflags |= (groupperm & mask) << 3;
1596 
1597 				} else if (acl_type(rep->aclp) == ACE_T) {
1598 					int mode;
1599 					mode = grp_mask_to_mode(rep->aclp);
1600 					rep->lflags &= ~S_IRWXG;
1601 					rep->lflags |= mode;
1602 				}
1603 			}
1604 
1605 			if (!vflg && !Vflg && rep->aclp) {
1606 				acl_free(rep->aclp);
1607 				rep->aclp = NULL;
1608 			}
1609 
1610 			if (atflg && pathconf(file, _PC_XATTR_EXISTS) == 1)
1611 				rep->acl = '@';
1612 
1613 		} else
1614 			rep->acl = ' ';
1615 
1616 		/* mask ISARG and other file-type bits */
1617 
1618 		rep->luid = statb.st_uid;
1619 		rep->lgid = statb.st_gid;
1620 		rep->lnl = statb.st_nlink;
1621 		if (uflg || (tmflg && atm))
1622 			rep->lmtime = statb.st_atim;
1623 		else if (cflg || (tmflg && ctm))
1624 			rep->lmtime = statb.st_ctim;
1625 		else
1626 			rep->lmtime = statb.st_mtim;
1627 		rep->lat = statb.st_atim;
1628 		rep->lct = statb.st_ctim;
1629 		rep->lmt = statb.st_mtim;
1630 
1631 		if (rep->ltype != 'b' && rep->ltype != 'c')
1632 			tblocks += rep->lblocks;
1633 
1634 		/* Get extended system attributes */
1635 
1636 		rep->exttr = NULL;
1637 		rep->extm = NULL;
1638 		if ((saflg || (tmflg && crtm) || (tmflg && alltm)) &&
1639 		    (sysattr_support(file, _PC_SATTR_EXISTS) == 1)) {
1640 			int i;
1641 
1642 			sacnt = attr_count();
1643 			/*
1644 			 * Allocate 'sacnt' size array to hold extended
1645 			 * system attribute name (verbose) or respective
1646 			 * symbol represenation (compact).
1647 			 */
1648 			rep->exttr = xmalloc(sacnt * sizeof (struct attrb),
1649 			    rep);
1650 
1651 			/* initialize boolean attribute list */
1652 			for (i = 0; i < sacnt; i++)
1653 				rep->exttr[i].name = NULL;
1654 			if (get_sysxattr(file, rep) != 0) {
1655 				(void) fprintf(stderr,
1656 				    gettext("ls:Failed to retrieve "
1657 				    "extended system attribute from "
1658 				    "%s\n"), file);
1659 				rep->exttr[0].name = xmalloc(2, rep);
1660 				(void) strlcpy(rep->exttr[0].name, "?", 2);
1661 			}
1662 		}
1663 	}
1664 	return (rep);
1665 }
1666 
1667 /*
1668  * returns pathname of the form dir/file;
1669  * dir and file are null-terminated strings.
1670  */
1671 static char *
1672 makename(char *dir, char *file)
1673 {
1674 	/*
1675 	 * PATH_MAX is the maximum length of a path name.
1676 	 * MAXNAMLEN is the maximum length of any path name component.
1677 	 * Allocate space for both, plus the '/' in the middle
1678 	 * and the null character at the end.
1679 	 * dfile is static as this is returned by makename().
1680 	 */
1681 	static char dfile[PATH_MAX + 1 + MAXNAMLEN + 1];
1682 	char *dp, *fp;
1683 
1684 	dp = dfile;
1685 	fp = dir;
1686 	while (*fp)
1687 		*dp++ = *fp++;
1688 	if (dp > dfile && *(dp - 1) != '/')
1689 		*dp++ = '/';
1690 	fp = file;
1691 	while (*fp)
1692 		*dp++ = *fp++;
1693 	*dp = '\0';
1694 	return (dfile);
1695 }
1696 
1697 
1698 #include <pwd.h>
1699 #include <grp.h>
1700 #include <utmpx.h>
1701 
1702 struct	utmpx utmp;
1703 
1704 #define	NMAX	(sizeof (utmp.ut_name))
1705 #define	SCPYN(a, b)	(void) strncpy(a, b, NMAX)
1706 
1707 
1708 struct cachenode {		/* this struct must be zeroed before using */
1709 	struct cachenode *lesschild;	/* subtree whose entries < val */
1710 	struct cachenode *grtrchild;	/* subtree whose entries > val */
1711 	long val;			/* the uid or gid of this entry */
1712 	int initted;			/* name has been filled in */
1713 	char name[NMAX+1];		/* the string that val maps to */
1714 };
1715 static struct cachenode *names, *groups;
1716 
1717 static struct cachenode *
1718 findincache(struct cachenode **head, long val)
1719 {
1720 	struct cachenode **parent = head;
1721 	struct cachenode *c = *parent;
1722 
1723 	while (c != NULL) {
1724 		if (val == c->val) {
1725 			/* found it */
1726 			return (c);
1727 		} else if (val < c->val) {
1728 			parent = &c->lesschild;
1729 			c = c->lesschild;
1730 		} else {
1731 			parent = &c->grtrchild;
1732 			c = c->grtrchild;
1733 		}
1734 	}
1735 
1736 	/* not in the cache, make a new entry for it */
1737 	c = calloc(1, sizeof (struct cachenode));
1738 	if (c == NULL) {
1739 		perror("ls");
1740 		exit(2);
1741 	}
1742 	*parent = c;
1743 	c->val = val;
1744 	return (c);
1745 }
1746 
1747 /*
1748  * get name from cache, or passwd file for a given uid;
1749  * lastuid is set to uid.
1750  */
1751 static char *
1752 getname(uid_t uid)
1753 {
1754 	struct passwd *pwent;
1755 	struct cachenode *c;
1756 
1757 	if ((uid == lastuid) && lastuname)
1758 		return (lastuname);
1759 
1760 	c = findincache(&names, uid);
1761 	if (c->initted == 0) {
1762 		if ((pwent = getpwuid(uid)) != NULL) {
1763 			SCPYN(&c->name[0], pwent->pw_name);
1764 		} else {
1765 			(void) sprintf(&c->name[0], "%-8u", (int)uid);
1766 		}
1767 		c->initted = 1;
1768 	}
1769 	lastuid = uid;
1770 	lastuname = &c->name[0];
1771 	return (lastuname);
1772 }
1773 
1774 /*
1775  * get name from cache, or group file for a given gid;
1776  * lastgid is set to gid.
1777  */
1778 static char *
1779 getgroup(gid_t gid)
1780 {
1781 	struct group *grent;
1782 	struct cachenode *c;
1783 
1784 	if ((gid == lastgid) && lastgname)
1785 		return (lastgname);
1786 
1787 	c = findincache(&groups, gid);
1788 	if (c->initted == 0) {
1789 		if ((grent = getgrgid(gid)) != NULL) {
1790 			SCPYN(&c->name[0], grent->gr_name);
1791 		} else {
1792 			(void) sprintf(&c->name[0], "%-8u", (int)gid);
1793 		}
1794 		c->initted = 1;
1795 	}
1796 	lastgid = gid;
1797 	lastgname = &c->name[0];
1798 	return (lastgname);
1799 }
1800 
1801 /* return >0 if item pointed by pp2 should appear first */
1802 static int
1803 compar(struct lbuf **pp1, struct lbuf **pp2)
1804 {
1805 	struct lbuf *p1, *p2;
1806 
1807 	p1 = *pp1;
1808 	p2 = *pp2;
1809 	if (dflg == 0) {
1810 /*
1811  * compare two names in ls-command one of which is file
1812  * and the other is a directory;
1813  * this portion is not used for comparing files within
1814  * a directory name of ls-command;
1815  */
1816 		if (p1->lflags&ISARG && p1->ltype == 'd') {
1817 			if (!(p2->lflags&ISARG && p2->ltype == 'd'))
1818 				return (1);
1819 		} else {
1820 			if (p2->lflags&ISARG && p2->ltype == 'd')
1821 				return (-1);
1822 		}
1823 	}
1824 	if (tflg) {
1825 		if (p2->lmtime.tv_sec > p1->lmtime.tv_sec)
1826 			return (rflg);
1827 		else if (p2->lmtime.tv_sec < p1->lmtime.tv_sec)
1828 			return (-rflg);
1829 		/* times are equal to the sec, check nsec */
1830 		if (p2->lmtime.tv_nsec > p1->lmtime.tv_nsec)
1831 			return (rflg);
1832 		else if (p2->lmtime.tv_nsec < p1->lmtime.tv_nsec)
1833 			return (-rflg);
1834 		/* if times are equal, fall through and sort by name */
1835 	} else if (Sflg) {
1836 		/*
1837 		 * The size stored in lsize can be either the
1838 		 * size or the major minor number (in the case of
1839 		 * block and character special devices).  If it's
1840 		 * a major minor number, then the size is considered
1841 		 * to be zero and we want to fall through and sort
1842 		 * by name.  In addition, if the size of p2 is equal
1843 		 * to the size of p1 we want to fall through and
1844 		 * sort by name.
1845 		 */
1846 		off_t	p1size = (p1->ltype == 'b') ||
1847 		    (p1->ltype == 'c') ? 0 : p1->lsize;
1848 		off_t	p2size = (p2->ltype == 'b') ||
1849 		    (p2->ltype == 'c') ? 0 : p2->lsize;
1850 		if (p2size > p1size) {
1851 			return (rflg);
1852 		} else if (p2size < p1size) {
1853 			return (-rflg);
1854 		}
1855 		/* Sizes are equal, fall through and sort by name. */
1856 	}
1857 	return (rflg * strcoll(
1858 	    p1->lflags & ISARG ? p1->ln.namep : p1->ln.lname,
1859 	    p2->lflags&ISARG ? p2->ln.namep : p2->ln.lname));
1860 }
1861 
1862 static void
1863 pprintf(char *s1, char *s2)
1864 {
1865 	csi_pprintf((unsigned char *)s1);
1866 	csi_pprintf((unsigned char *)s2);
1867 }
1868 
1869 static void
1870 csi_pprintf(unsigned char *s)
1871 {
1872 	unsigned char *cp;
1873 	char	c;
1874 	int	i;
1875 	int	c_len;
1876 	int	p_col;
1877 	wchar_t	pcode;
1878 
1879 	if (!qflg && !bflg) {
1880 		for (cp = s; *cp != '\0'; cp++) {
1881 			(void) putchar(*cp);
1882 			curcol++;
1883 		}
1884 		return;
1885 	}
1886 
1887 	for (cp = s; *cp; ) {
1888 		if (isascii(c = *cp)) {
1889 			if (!isprint(c)) {
1890 				if (qflg) {
1891 					c = '?';
1892 				} else {
1893 					curcol += 3;
1894 					(void) putc('\\', stdout);
1895 					c = '0' + ((*cp >> 6) & 07);
1896 					(void) putc(c, stdout);
1897 					c = '0' + ((*cp >> 3) & 07);
1898 					(void) putc(c, stdout);
1899 					c = '0' + (*cp & 07);
1900 				}
1901 			}
1902 			curcol++;
1903 			cp++;
1904 			(void) putc(c, stdout);
1905 			continue;
1906 		}
1907 
1908 		if ((c_len = mbtowc(&pcode, (char *)cp, MB_LEN_MAX)) <= 0) {
1909 			c_len = 1;
1910 			goto not_print;
1911 		}
1912 
1913 		if ((p_col = wcwidth(pcode)) > 0) {
1914 			(void) putwchar(pcode);
1915 			cp += c_len;
1916 			curcol += p_col;
1917 			continue;
1918 		}
1919 
1920 not_print:
1921 		for (i = 0; i < c_len; i++) {
1922 			if (qflg) {
1923 				c = '?';
1924 			} else {
1925 				curcol += 3;
1926 				(void) putc('\\', stdout);
1927 				c = '0' + ((*cp >> 6) & 07);
1928 				(void) putc(c, stdout);
1929 				c = '0' + ((*cp >> 3) & 07);
1930 				(void) putc(c, stdout);
1931 				c = '0' + (*cp & 07);
1932 			}
1933 			curcol++;
1934 			(void) putc(c, stdout);
1935 			cp++;
1936 		}
1937 	}
1938 }
1939 
1940 static int
1941 strcol(unsigned char *s1)
1942 {
1943 	int	w;
1944 	int	w_col;
1945 	int	len;
1946 	wchar_t	wc;
1947 
1948 	w = 0;
1949 	while (*s1) {
1950 		if (isascii(*s1)) {
1951 			w++;
1952 			s1++;
1953 			continue;
1954 		}
1955 
1956 		if ((len = mbtowc(&wc, (char *)s1, MB_LEN_MAX)) <= 0) {
1957 			w++;
1958 			s1++;
1959 			continue;
1960 		}
1961 
1962 		if ((w_col = wcwidth(wc)) < 0)
1963 			w_col = len;
1964 		s1 += len;
1965 		w += w_col;
1966 	}
1967 	return (w);
1968 }
1969 
1970 /*
1971  * Convert an unsigned long long to a string representation and place the
1972  * result in the caller-supplied buffer.
1973  *
1974  * The number provided is a size in bytes.  The number is first
1975  * converted to an integral multiple of 'scale' bytes.  This new
1976  * number is then scaled down until it is small enough to be in a good
1977  * human readable format, i.e.  in the range 0 thru scale-1.  If the
1978  * number used to derive the final number is not a multiple of scale, and
1979  * the final number has only a single significant digit, we compute
1980  * tenths of units to provide a second significant digit.
1981  *
1982  * The value "(unsigned long long)-1" is a special case and is always
1983  * converted to "-1".
1984  *
1985  * A pointer to the caller-supplied buffer is returned.
1986  */
1987 static char *
1988 number_to_scaled_string(
1989 			numbuf_t buf,		/* put the result here */
1990 			unsigned long long number, /* convert this number */
1991 			long scale)
1992 {
1993 	unsigned long long save;
1994 	/* Measurement: kilo, mega, giga, tera, peta, exa */
1995 	char *uom = "KMGTPE";
1996 
1997 	if ((long long)number == (long long)-1) {
1998 		(void) strlcpy(buf, "-1", sizeof (numbuf_t));
1999 		return (buf);
2000 	}
2001 
2002 	save = number;
2003 	number = number / scale;
2004 
2005 	/*
2006 	 * Now we have number as a count of scale units.
2007 	 * If no further scaling is necessary, we round up as appropriate.
2008 	 *
2009 	 * The largest value number could have had entering the routine is
2010 	 * 16 Exabytes, so running off the end of the uom array should
2011 	 * never happen.  We check for that, though, as a guard against
2012 	 * a breakdown elsewhere in the algorithm.
2013 	 */
2014 	if (number < (unsigned long long)scale) {
2015 		if ((save % scale) >= (unsigned long long)(scale / 2)) {
2016 			if (++number == (unsigned long long)scale) {
2017 				uom++;
2018 				number = 1;
2019 			}
2020 		}
2021 	} else {
2022 		while ((number >= (unsigned long long)scale) && (*uom != 'E')) {
2023 			uom++; /* next unit of measurement */
2024 			save = number;
2025 			/*
2026 			 * If we're over half way to the next unit of
2027 			 * 'scale' bytes (which means we should round
2028 			 * up), then adding half of 'scale' prior to
2029 			 * the division will push us into that next
2030 			 * unit of scale when we perform the division
2031 			 */
2032 			number = (number + (scale / 2)) / scale;
2033 		}
2034 	}
2035 
2036 	/* check if we should output a decimal place after the point */
2037 	if ((save / scale) < 10) {
2038 		/* snprintf() will round for us */
2039 		float fnum = (float)save / scale;
2040 		(void) snprintf(buf, sizeof (numbuf_t), "%2.1f%c",
2041 		    fnum, *uom);
2042 	} else {
2043 		(void) snprintf(buf, sizeof (numbuf_t), "%4llu%c",
2044 		    number, *uom);
2045 	}
2046 	return (buf);
2047 }
2048 
2049 /* Get extended system attributes and set the display */
2050 
2051 int
2052 get_sysxattr(char *fname, struct lbuf *rep)
2053 {
2054 	boolean_t	value;
2055 	data_type_t	type;
2056 	int		error;
2057 	char		*name;
2058 	int		i;
2059 
2060 	if ((error = getattrat(AT_FDCWD, XATTR_VIEW_READWRITE, fname,
2061 	    &response)) != 0) {
2062 		perror("ls:getattrat");
2063 		return (error);
2064 	}
2065 
2066 	/*
2067 	 * Allocate 'sacnt' size array to hold extended timestamp
2068 	 * system attributes and initialize the array.
2069 	 */
2070 	rep->extm = xmalloc(sacnt * sizeof (struct attrtm), rep);
2071 	for (i = 0; i < sacnt; i++) {
2072 		rep->extm[i].stm = 0;
2073 		rep->extm[i].nstm = 0;
2074 		rep->extm[i].name = NULL;
2075 	}
2076 	while ((pair = nvlist_next_nvpair(response, pair)) != NULL) {
2077 		name = nvpair_name(pair);
2078 		type = nvpair_type(pair);
2079 		if (type == DATA_TYPE_BOOLEAN_VALUE) {
2080 			error = nvpair_value_boolean_value(pair, &value);
2081 			if (error) {
2082 				(void) fprintf(stderr,
2083 				    gettext("nvpair_value_boolean_value "
2084 				    "failed: error = %d\n"), error);
2085 				continue;
2086 			}
2087 			if (name != NULL)
2088 				set_sysattrb_display(name, value, rep);
2089 			continue;
2090 		} else if (type == DATA_TYPE_UINT64_ARRAY) {
2091 			if (name != NULL)
2092 				set_sysattrtm_display(name, rep);
2093 			continue;
2094 		}
2095 	}
2096 	nvlist_free(response);
2097 	return (0);
2098 }
2099 
2100 /* Set extended system attribute boolean display */
2101 
2102 void
2103 set_sysattrb_display(char *name, boolean_t val, struct lbuf *rep)
2104 {
2105 	f_attr_t	fattr;
2106 	const char	*opt;
2107 	size_t		len;
2108 
2109 	fattr = name_to_attr(name);
2110 	if (fattr != F_ATTR_INVAL && fattr < sacnt) {
2111 		if (vopt) {
2112 			len = strlen(name);
2113 			if (val) {
2114 				rep->exttr[fattr].name = xmalloc(len + 1, rep);
2115 				(void) strlcpy(rep->exttr[fattr].name, name,
2116 				    len + 1);
2117 			} else {
2118 				rep->exttr[fattr].name = xmalloc(len + 3, rep);
2119 				(void) snprintf(rep->exttr[fattr].name, len + 3,
2120 				    "no%s", name);
2121 			}
2122 		} else {
2123 			opt = attr_to_option(fattr);
2124 			if (opt != NULL) {
2125 				len = strlen(opt);
2126 				rep->exttr[fattr].name = xmalloc(len + 1, rep);
2127 				if (val)
2128 					(void) strlcpy(rep->exttr[fattr].name,
2129 					    opt, len + 1);
2130 				else
2131 					(void) strlcpy(rep->exttr[fattr].name,
2132 					    "-", len + 1);
2133 			}
2134 		}
2135 	}
2136 }
2137 
2138 /* Set extended system attribute timestamp display */
2139 
2140 void
2141 set_sysattrtm_display(char *name, struct lbuf *rep)
2142 {
2143 	uint_t		nelem;
2144 	uint64_t	*value;
2145 	int		i;
2146 	size_t		len;
2147 
2148 	if (nvpair_value_uint64_array(pair, &value, &nelem) == 0) {
2149 		if (*value != NULL) {
2150 			len = strlen(name);
2151 			i = 0;
2152 			while (rep->extm[i].stm != 0 && i < sacnt)
2153 				i++;
2154 			rep->extm[i].stm = value[0];
2155 			rep->extm[i].nstm = value[1];
2156 			rep->extm[i].name = xmalloc(len + 1, rep);
2157 			(void) strlcpy(rep->extm[i].name, name, len + 1);
2158 		}
2159 	}
2160 }
2161 
2162 void
2163 format_time(const char *format, time_t sec)
2164 {
2165 
2166 	(void) strftime(time_buf, sizeof (time_buf),
2167 	    dcgettext(NULL, format, LC_TIME),
2168 	    localtime(&sec));
2169 }
2170 
2171 void
2172 format_etime(const char *format, time_t sec, time_t nsec)
2173 {
2174 	char fmt_buf[FMTSIZE];
2175 
2176 	(void) snprintf(fmt_buf, FMTSIZE,
2177 	    format, nsec);
2178 	(void) strftime(time_buf, sizeof (time_buf),
2179 	    fmt_buf, localtime(&sec));
2180 }
2181 
2182 /* Format timestamp extended system attributes */
2183 
2184 void
2185 format_attrtime(struct lbuf *p)
2186 {
2187 	int	tmattr = 0;
2188 	int i;
2189 
2190 	if (p->extm != NULL) {
2191 		for (i = 0; i < sacnt; i++) {
2192 			if (p->extm[i].name != NULL) {
2193 				tmattr = 1;
2194 				break;
2195 			}
2196 		}
2197 	}
2198 	if (tmattr) {
2199 		if (Eflg)
2200 			format_etime(FORMAT4, (time_t)p->extm[i].stm,
2201 			    (time_t)p->extm[i].nstm);
2202 		else  {
2203 			if ((p->lmtime.tv_sec < year) ||
2204 			    (p->lmtime.tv_sec > now))
2205 				format_time(FORMAT1,
2206 				    (time_t)p->extm[i].stm);
2207 			else
2208 				format_time(FORMAT2,
2209 				    (time_t)p->extm[i].stm);
2210 		}
2211 	}
2212 }
2213 
2214 void
2215 print_time(struct lbuf *p)
2216 {
2217 	int i = 0;
2218 
2219 	new_line();
2220 	if (Eflg) {
2221 		format_etime(FORMAT4, p->lat.tv_sec, p->lat.tv_nsec);
2222 		(void) printf("		timestamp: atime	%s\n",
2223 		    time_buf);
2224 		format_etime(FORMAT4, p->lct.tv_sec, p->lct.tv_nsec);
2225 		(void) printf("		timestamp: ctime	%s\n",
2226 		    time_buf);
2227 		format_etime(FORMAT4, p->lmt.tv_sec, p->lmt.tv_nsec);
2228 		(void) printf("		timestamp: mtime	%s\n",
2229 		    time_buf);
2230 		if (p->extm != NULL) {
2231 			while (p->extm[i].nstm != 0 && i < sacnt) {
2232 				format_etime(FORMAT4, p->extm[i].stm,
2233 				    p->extm[i].nstm);
2234 				if (p->extm[i].name != NULL) {
2235 					(void) printf("		timestamp:"
2236 					    " %s	%s\n",
2237 					    p->extm[i].name, time_buf);
2238 				}
2239 				i++;
2240 			}
2241 		}
2242 	} else {
2243 		format_time(FORMAT3, p->lat.tv_sec);
2244 		(void) printf("		timestamp: atime	%s\n",
2245 		    time_buf);
2246 		format_time(FORMAT3, p->lct.tv_sec);
2247 		(void) printf("		timestamp: ctime	%s\n",
2248 		    time_buf);
2249 		format_time(FORMAT3, p->lmt.tv_sec);
2250 		(void) printf("		timestamp: mtime	%s\n",
2251 		    time_buf);
2252 		if (p->extm != NULL) {
2253 			while (p->extm[i].stm != 0 && i < sacnt) {
2254 				format_time(FORMAT3, p->extm[i].stm);
2255 				if (p->extm[i].name != NULL) {
2256 					(void) printf("		timestamp:"
2257 					    " %s	%s\n",
2258 					    p->extm[i].name, time_buf);
2259 				}
2260 				i++;
2261 			}
2262 		}
2263 	}
2264 }
2265 
2266 /* Free extended system attribute lists */
2267 
2268 void
2269 free_sysattr(struct lbuf *p)
2270 {
2271 	int i;
2272 
2273 	if (p->exttr != NULL) {
2274 		for (i = 0; i < sacnt; i++) {
2275 			if (p->exttr[i].name != NULL)
2276 				free(p->exttr[i].name);
2277 		}
2278 		free(p->exttr);
2279 	}
2280 	if (p->extm != NULL) {
2281 		for (i = 0; i < sacnt; i++) {
2282 			if (p->extm[i].name != NULL)
2283 				free(p->extm[i].name);
2284 		}
2285 		free(p->extm);
2286 	}
2287 }
2288 
2289 /* Allocate extended system attribute list */
2290 
2291 void *
2292 xmalloc(size_t size, struct lbuf *p)
2293 {
2294 	if ((p = malloc(size)) == NULL) {
2295 		perror("ls");
2296 		free_sysattr(p);
2297 		nvlist_free(response);
2298 		exit(2);
2299 	}
2300 	return (p);
2301 }
2302