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