xref: /freebsd/bin/ps/ps.c (revision 2357939bc239bd5334a169b62313806178dd8f30)
1 /*-
2  * Copyright (c) 1990, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  * ------+---------+---------+-------- + --------+---------+---------+---------*
29  * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
30  * All rights reserved.
31  *
32  * Significant modifications made to bring `ps' options somewhat closer
33  * to the standard for `ps' as described in SingleUnixSpec-v3.
34  * ------+---------+---------+-------- + --------+---------+---------+---------*
35  */
36 
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1990, 1993, 1994\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #if 0
44 #ifndef lint
45 static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
46 #endif /* not lint */
47 #endif
48 
49 #include <sys/cdefs.h>
50 __FBSDID("$FreeBSD$");
51 
52 #include <sys/param.h>
53 #include <sys/proc.h>
54 #include <sys/user.h>
55 #include <sys/stat.h>
56 #include <sys/ioctl.h>
57 #include <sys/sysctl.h>
58 
59 #include <ctype.h>
60 #include <err.h>
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <grp.h>
64 #include <kvm.h>
65 #include <limits.h>
66 #include <locale.h>
67 #include <paths.h>
68 #include <pwd.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
73 
74 #include "ps.h"
75 
76 #define	W_SEP	" \t"		/* "Whitespace" list separators */
77 #define	T_SEP	","		/* "Terminate-element" list separators */
78 
79 #ifdef LAZY_PS
80 #define	DEF_UREAD	0
81 #define	OPT_LAZY_f	"f"
82 #else
83 #define	DEF_UREAD	1	/* Always do the more-expensive read. */
84 #define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
85 #endif
86 
87 int	 cflag;			/* -c */
88 int	 eval;			/* Exit value */
89 time_t	 now;			/* Current time(3) value */
90 int	 rawcpu;		/* -C */
91 int	 sumrusage;		/* -S */
92 int	 termwidth;		/* Width of the screen (0 == infinity). */
93 int	 totwidth;		/* Calculated-width of requested variables. */
94 
95 struct varent *vhead;
96 
97 static int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
98 static kvm_t	*kd;
99 static KINFO	*kinfo;
100 static int	 needcomm;	/* -o "command" */
101 static int	 needenv;	/* -e */
102 static int	 needuser;	/* -o "user" */
103 static int	 optfatal;	/* Fatal error parsing some list-option. */
104 
105 static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
106 
107 struct listinfo;
108 typedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
109 
110 struct listinfo {
111 	int		 count;
112 	int		 maxcount;
113 	int		 elemsize;
114 	addelem_rtn	*addelem;
115 	const char	*lname;
116 	union {
117 		gid_t	*gids;
118 		pid_t	*pids;
119 		dev_t	*ttys;
120 		uid_t	*uids;
121 		void	*ptr;
122 	} l;
123 };
124 
125 static int	 addelem_gid(struct listinfo *, const char *);
126 static int	 addelem_pid(struct listinfo *, const char *);
127 static int	 addelem_tty(struct listinfo *, const char *);
128 static int	 addelem_uid(struct listinfo *, const char *);
129 static void	 add_list(struct listinfo *, const char *);
130 static void	 dynsizevars(KINFO *);
131 static void	*expand_list(struct listinfo *);
132 static const char *
133 		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
134 		    KINFO *, char *, int);
135 static void	 free_list(struct listinfo *);
136 static void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
137 static char	*kludge_oldps_options(char *);
138 static int	 pscomp(const void *, const void *);
139 static void	 saveuser(KINFO *);
140 static void	 scanvars(void);
141 static void	 sizevars(void);
142 static void	 usage(void);
143 
144 static char dfmt[] = "pid,tt,state,time,command";
145 static char jfmt[] = "user,pid,ppid,pgid,jobc,state,tt,time,command";
146 static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
147 			"tt,time,command";
148 static char   o1[] = "pid";
149 static char   o2[] = "tt,state,time,command";
150 static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
151 static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
152 			"%cpu,%mem,command";
153 static char Zfmt[] = "label";
154 
155 #define	PS_ARGS	"AaCce" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
156 
157 int
158 main(int argc, char *argv[])
159 {
160 	struct listinfo gidlist, pgrplist, pidlist;
161 	struct listinfo ruidlist, sesslist, ttylist, uidlist;
162 	struct kinfo_proc *kp;
163 	struct varent *vent;
164 	struct winsize ws;
165 	const char *cp, *nlistf, *memf;
166 	char *cols;
167 	int all, ch, dropgid, elem, flag, _fmt, i, lineno;
168 	int nentries, nocludge, nkept, nselectors;
169 	int prtheader, showthreads, wflag, what, xkeep, xkeep_implied;
170 	char errbuf[_POSIX2_LINE_MAX];
171 
172 	(void) setlocale(LC_ALL, "");
173 	time(&now);			/* Used by routines in print.c. */
174 
175 	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
176 		termwidth = atoi(cols);
177 	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
178 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
179 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
180 	     ws.ws_col == 0)
181 		termwidth = 79;
182 	else
183 		termwidth = ws.ws_col - 1;
184 
185 	/*
186 	 * Don't apply a kludge if the first argument is an option taking an
187 	 * argument
188 	 */
189 	if (argc > 1) {
190 		nocludge = 0;
191 		if (argv[1][0] == '-') {
192 			for (cp = PS_ARGS; *cp != '\0'; cp++) {
193 				if (*cp != ':')
194 					continue;
195 				if (*(cp - 1) == argv[1][1]) {
196 					nocludge = 1;
197 					break;
198 				}
199 			}
200 		}
201 		if (nocludge == 0)
202 			argv[1] = kludge_oldps_options(argv[1]);
203 	}
204 
205 	all = dropgid = _fmt = nselectors = optfatal = 0;
206 	prtheader = showthreads = wflag = xkeep_implied = 0;
207 	xkeep = -1;			/* Neither -x nor -X. */
208 	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
209 	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
210 	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
211 	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
212 	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
213 	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
214 	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
215 	memf = nlistf = _PATH_DEVNULL;
216 	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
217 		switch((char)ch) {
218 		case 'A':
219 			/*
220 			 * Exactly the same as `-ax'.   This has been
221 			 * added for compatability with SUSv3, but for
222 			 * now it will not be described in the man page.
223 			 */
224 			nselectors++;
225 			all = xkeep = 1;
226 			break;
227 		case 'a':
228 			nselectors++;
229 			all = 1;
230 			break;
231 		case 'C':
232 			rawcpu = 1;
233 			break;
234 		case 'c':
235 			cflag = 1;
236 			break;
237 		case 'e':			/* XXX set ufmt */
238 			needenv = 1;
239 			break;
240 #ifdef LAZY_PS
241 		case 'f':
242 			if (getuid() == 0 || getgid() == 0)
243 				forceuread = 1;
244 			break;
245 #endif
246 		case 'G':
247 			add_list(&gidlist, optarg);
248 			xkeep_implied = 1;
249 			nselectors++;
250 			break;
251 		case 'g':
252 #if 0
253 			/*-
254 			 * XXX - This SUSv3 behavior is still under debate
255 			 *	since it conflicts with the (undocumented)
256 			 *	`-g' option.  So we skip it for now.
257 			 */
258 			add_list(&pgrplist, optarg);
259 			xkeep_implied = 1;
260 			nselectors++;
261 			break;
262 #else
263 			/* The historical BSD-ish (from SunOS) behavior. */
264 			break;			/* no-op */
265 #endif
266 		case 'H':
267 			showthreads = KERN_PROC_INC_THREAD;
268 			break;
269 		case 'h':
270 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
271 			break;
272 		case 'j':
273 			parsefmt(jfmt, 0);
274 			_fmt = 1;
275 			jfmt[0] = '\0';
276 			break;
277 		case 'L':
278 			showkey();
279 			exit(0);
280 		case 'l':
281 			parsefmt(lfmt, 0);
282 			_fmt = 1;
283 			lfmt[0] = '\0';
284 			break;
285 		case 'M':
286 			memf = optarg;
287 			dropgid = 1;
288 			break;
289 		case 'm':
290 			sortby = SORTMEM;
291 			break;
292 		case 'N':
293 			nlistf = optarg;
294 			dropgid = 1;
295 			break;
296 		case 'O':
297 			parsefmt(o1, 1);
298 			parsefmt(optarg, 1);
299 			parsefmt(o2, 1);
300 			o1[0] = o2[0] = '\0';
301 			_fmt = 1;
302 			break;
303 		case 'o':
304 			parsefmt(optarg, 1);
305 			_fmt = 1;
306 			break;
307 		case 'p':
308 			add_list(&pidlist, optarg);
309 			/*
310 			 * Note: `-p' does not *set* xkeep, but any values
311 			 * from pidlist are checked before xkeep is.  That
312 			 * way they are always matched, even if the user
313 			 * specifies `-X'.
314 			 */
315 			nselectors++;
316 			break;
317 #if 0
318 		case 'R':
319 			/*-
320 			 * XXX - This un-standard option is still under
321 			 *	debate.  This is what SUSv3 defines as
322 			 *	the `-U' option, and while it would be
323 			 *	nice to have, it could cause even more
324 			 *	confusion to implement it as `-R'.
325 			 */
326 			add_list(&ruidlist, optarg);
327 			xkeep_implied = 1;
328 			nselectors++;
329 			break;
330 #endif
331 		case 'r':
332 			sortby = SORTCPU;
333 			break;
334 		case 'S':
335 			sumrusage = 1;
336 			break;
337 #if 0
338 		case 's':
339 			/*-
340 			 * XXX - This non-standard option is still under
341 			 *	debate.  This *is* supported on Solaris,
342 			 *	Linux, and IRIX, but conflicts with `-s'
343 			 *	on NetBSD and maybe some older BSD's.
344 			 */
345 			add_list(&sesslist, optarg);
346 			xkeep_implied = 1;
347 			nselectors++;
348 			break;
349 #endif
350 		case 'T':
351 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
352 				errx(1, "stdin: not a terminal");
353 			/* FALLTHROUGH */
354 		case 't':
355 			add_list(&ttylist, optarg);
356 			xkeep_implied = 1;
357 			nselectors++;
358 			break;
359 		case 'U':
360 			/* This is what SUSv3 defines as the `-u' option. */
361 			add_list(&uidlist, optarg);
362 			xkeep_implied = 1;
363 			nselectors++;
364 			break;
365 		case 'u':
366 			parsefmt(ufmt, 0);
367 			sortby = SORTCPU;
368 			_fmt = 1;
369 			ufmt[0] = '\0';
370 			break;
371 		case 'v':
372 			parsefmt(vfmt, 0);
373 			sortby = SORTMEM;
374 			_fmt = 1;
375 			vfmt[0] = '\0';
376 			break;
377 		case 'w':
378 			if (wflag)
379 				termwidth = UNLIMITED;
380 			else if (termwidth < 131)
381 				termwidth = 131;
382 			wflag++;
383 			break;
384 		case 'X':
385 			/*
386 			 * Note that `-X' and `-x' are not standard "selector"
387 			 * options. For most selector-options, we check *all*
388 			 * processes to see if any are matched by the given
389 			 * value(s).  After we have a set of all the matched
390 			 * processes, then `-X' and `-x' govern whether we
391 			 * modify that *matched* set for processes which do
392 			 * not have a controlling terminal.  `-X' causes
393 			 * those processes to be deleted from the matched
394 			 * set, while `-x' causes them to be kept.
395 			 */
396 			xkeep = 0;
397 			break;
398 		case 'x':
399 			xkeep = 1;
400 			break;
401 		case 'Z':
402 			parsefmt(Zfmt, 0);
403 			Zfmt[0] = '\0';
404 			break;
405 		case '?':
406 		default:
407 			usage();
408 		}
409 	argc -= optind;
410 	argv += optind;
411 	if (optfatal)
412 		exit(1);		/* Error messages already printed. */
413 	if (xkeep < 0)			/* Neither -X nor -x was specified. */
414 		xkeep = xkeep_implied;
415 
416 #define	BACKWARD_COMPATIBILITY
417 #ifdef	BACKWARD_COMPATIBILITY
418 	if (*argv) {
419 		nlistf = *argv;
420 		if (*++argv)
421 			memf = *argv;
422 	}
423 #endif
424 	/*
425 	 * Discard setgid privileges if not the running kernel so that bad
426 	 * guys can't print interesting stuff from kernel memory.
427 	 */
428 	if (dropgid) {
429 		setgid(getgid());
430 		setuid(getuid());
431 	}
432 
433 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
434 	if (kd == 0)
435 		errx(1, "%s", errbuf);
436 
437 	if (!_fmt)
438 		parsefmt(dfmt, 0);
439 
440 	if (nselectors == 0) {
441 		uidlist.l.ptr = malloc(sizeof(uid_t));
442 		if (uidlist.l.ptr == NULL)
443 			errx(1, "malloc failed");
444 		nselectors = 1;
445 		uidlist.count = uidlist.maxcount = 1;
446 		*uidlist.l.uids = getuid();
447 	}
448 
449 	/*
450 	 * scan requested variables, noting what structures are needed,
451 	 * and adjusting header widths as appropriate.
452 	 */
453 	scanvars();
454 
455 	/*
456 	 * Get process list.  If the user requested just one selector-
457 	 * option, then kvm_getprocs can be asked to return just those
458 	 * processes.  Otherwise, have it return all processes, and
459 	 * then this routine will search that full list and select the
460 	 * processes which match any of the user's selector-options.
461 	 */
462 	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
463 	flag = 0;
464 	if (nselectors == 1) {
465 		/* XXX - Apparently there's no KERN_PROC_GID flag. */
466 		if (pgrplist.count == 1) {
467 			what = KERN_PROC_PGRP | showthreads;
468 			flag = *pgrplist.l.pids;
469 			nselectors = 0;
470 		} else if (pidlist.count == 1) {
471 			what = KERN_PROC_PID | showthreads;
472 			flag = *pidlist.l.pids;
473 			nselectors = 0;
474 		} else if (ruidlist.count == 1) {
475 			what = KERN_PROC_RUID | showthreads;
476 			flag = *ruidlist.l.uids;
477 			nselectors = 0;
478 #if 0
479 		/*-
480 		 * XXX - KERN_PROC_SESSION causes error in kvm_getprocs?
481 		 *	For now, always do sid-matching in this routine.
482 		 */
483 		} else if (sesslist.count == 1) {
484 			what = KERN_PROC_SESSION | showthreads;
485 			flag = *sesslist.l.pids;
486 			nselectors = 0;
487 #endif
488 		} else if (ttylist.count == 1) {
489 			what = KERN_PROC_TTY | showthreads;
490 			flag = *ttylist.l.ttys;
491 			nselectors = 0;
492 		} else if (uidlist.count == 1) {
493 			what = KERN_PROC_UID | showthreads;
494 			flag = *uidlist.l.uids;
495 			nselectors = 0;
496 		} else if (all) {
497 			/* No need for this routine to select processes. */
498 			nselectors = 0;
499 		}
500 	}
501 
502 	/*
503 	 * select procs
504 	 */
505 	nentries = -1;
506 	kp = kvm_getprocs(kd, what, flag, &nentries);
507 	if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
508 		errx(1, "%s", kvm_geterr(kd));
509 	nkept = 0;
510 	if (nentries > 0) {
511 		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
512 			errx(1, "malloc failed");
513 		for (i = nentries; --i >= 0; ++kp) {
514 			/*
515 			 * If the user specified multiple selection-criteria,
516 			 * then keep any process matched by the inclusive OR
517 			 * of all the selection-criteria given.
518 			 */
519 			if (pidlist.count > 0) {
520 				for (elem = 0; elem < pidlist.count; elem++)
521 					if (kp->ki_pid == pidlist.l.pids[elem])
522 						goto keepit;
523 			}
524 			/*
525 			 * Note that we had to process pidlist before
526 			 * filtering out processes which do not have
527 			 * a controlling terminal.
528 			 */
529 			if (xkeep == 0) {
530 				if ((kp->ki_tdev == NODEV ||
531 				    (kp->ki_flag & P_CONTROLT) == 0))
532 					continue;
533 			}
534 			if (nselectors == 0)
535 				goto keepit;
536 			if (gidlist.count > 0) {
537 				for (elem = 0; elem < gidlist.count; elem++)
538 					if (kp->ki_rgid == gidlist.l.gids[elem])
539 						goto keepit;
540 			}
541 			if (pgrplist.count > 0) {
542 				for (elem = 0; elem < pgrplist.count; elem++)
543 					if (kp->ki_pgid ==
544 					    pgrplist.l.pids[elem])
545 						goto keepit;
546 			}
547 			if (ruidlist.count > 0) {
548 				for (elem = 0; elem < ruidlist.count; elem++)
549 					if (kp->ki_ruid ==
550 					    ruidlist.l.uids[elem])
551 						goto keepit;
552 			}
553 			if (sesslist.count > 0) {
554 				for (elem = 0; elem < sesslist.count; elem++)
555 					if (kp->ki_sid == sesslist.l.pids[elem])
556 						goto keepit;
557 			}
558 			if (ttylist.count > 0) {
559 				for (elem = 0; elem < ttylist.count; elem++)
560 					if (kp->ki_tdev == ttylist.l.ttys[elem])
561 						goto keepit;
562 			}
563 			if (uidlist.count > 0) {
564 				for (elem = 0; elem < uidlist.count; elem++)
565 					if (kp->ki_uid == uidlist.l.uids[elem])
566 						goto keepit;
567 			}
568 			/*
569 			 * This process did not match any of the user's
570 			 * selector-options, so skip the process.
571 			 */
572 			continue;
573 
574 		keepit:
575 			kinfo[nkept].ki_p = kp;
576 			if (needuser)
577 				saveuser(&kinfo[nkept]);
578 			dynsizevars(&kinfo[nkept]);
579 			nkept++;
580 		}
581 	}
582 
583 	sizevars();
584 
585 	/*
586 	 * print header
587 	 */
588 	printheader();
589 	if (nkept == 0)
590 		exit(1);
591 
592 	/*
593 	 * sort proc list
594 	 */
595 	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
596 	/*
597 	 * For each process, call each variable output function.
598 	 */
599 	for (i = lineno = 0; i < nkept; i++) {
600 		for (vent = vhead; vent; vent = vent->next) {
601 			(vent->var->oproc)(&kinfo[i], vent);
602 			if (vent->next != NULL)
603 				(void)putchar(' ');
604 		}
605 		(void)putchar('\n');
606 		if (prtheader && lineno++ == prtheader - 4) {
607 			(void)putchar('\n');
608 			printheader();
609 			lineno = 0;
610 		}
611 	}
612 	free_list(&gidlist);
613 	free_list(&pidlist);
614 	free_list(&pgrplist);
615 	free_list(&ruidlist);
616 	free_list(&sesslist);
617 	free_list(&ttylist);
618 	free_list(&uidlist);
619 
620 	exit(eval);
621 }
622 
623 static int
624 addelem_gid(struct listinfo *inf, const char *elem)
625 {
626 	struct group *grp;
627 	const char *nameorID;
628 	char *endp;
629 	u_long bigtemp;
630 
631 	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
632 		if (*elem == '\0')
633 			warnx("Invalid (zero-length) %s name", inf->lname);
634 		else
635 			warnx("%s name too long: %s", inf->lname, elem);
636 		optfatal = 1;
637 		return (0);		/* Do not add this value. */
638 	}
639 
640 	/*
641 	 * SUSv3 states that `ps -G grouplist' should match "real-group
642 	 * ID numbers", and does not mention group-names.  I do want to
643 	 * also support group-names, so this tries for a group-id first,
644 	 * and only tries for a name if that doesn't work.  This is the
645 	 * opposite order of what is done in addelem_uid(), but in
646 	 * practice the order would only matter for group-names which
647 	 * are all-numeric.
648 	 */
649 	grp = NULL;
650 	nameorID = "named";
651 	errno = 0;
652 	bigtemp = strtoul(elem, &endp, 10);
653 	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
654 		nameorID = "name or ID matches";
655 		grp = getgrgid((gid_t)bigtemp);
656 	}
657 	if (grp == NULL)
658 		grp = getgrnam(elem);
659 	if (grp == NULL) {
660 		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
661 		optfatal = 1;
662 		return (0);		/* Do not add this value. */
663 	}
664 
665 	if (inf->count >= inf->maxcount)
666 		expand_list(inf);
667 	inf->l.gids[(inf->count)++] = grp->gr_gid;
668 	return (1);
669 }
670 
671 #define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h. */
672 static int
673 addelem_pid(struct listinfo *inf, const char *elem)
674 {
675 	char *endp;
676 	long tempid;
677 
678 	if (*elem == '\0')
679 		tempid = 0L;
680 	else {
681 		errno = 0;
682 		tempid = strtol(elem, &endp, 10);
683 		if (*endp != '\0' || tempid < 0 || elem == endp) {
684 			warnx("Invalid %s: %s", inf->lname, elem);
685 			errno = ERANGE;
686 		} else if (errno != 0 || tempid > BSD_PID_MAX) {
687 			warnx("%s too large: %s", inf->lname, elem);
688 			errno = ERANGE;
689 		}
690 		if (errno == ERANGE) {
691 			optfatal = 1;
692 			return (0);	/* Do not add this value. */
693 		}
694 	}
695 
696 	if (inf->count >= inf->maxcount)
697 		expand_list(inf);
698 	inf->l.pids[(inf->count)++] = tempid;
699 	return (1);
700 }
701 #undef	BSD_PID_MAX
702 
703 static int
704 addelem_tty(struct listinfo *inf, const char *elem)
705 {
706 	const char *ttypath;
707 	struct stat sb;
708 	char pathbuf[PATH_MAX];
709 
710 	if (strcmp(elem, "co") == 0)
711 		ttypath = strdup(_PATH_CONSOLE);
712 	else if (*elem == '/')
713 		ttypath = elem;
714 	else {
715 		strlcpy(pathbuf, _PATH_TTY, sizeof(pathbuf));
716 		strlcat(pathbuf, elem, sizeof(pathbuf));
717 		ttypath = pathbuf;
718 	}
719 
720 	if (stat(ttypath, &sb) == -1) {
721 		warn("%s", ttypath);
722 		optfatal = 1;
723 		return (0);		/* Do not add this value. */
724 	}
725 	if (!S_ISCHR(sb.st_mode)) {
726 		warn("%s: Not a terminal", ttypath);
727 		optfatal = 1;
728 		return (0);		/* Do not add this value. */
729 	}
730 
731 	if (inf->count >= inf->maxcount)
732 		expand_list(inf);
733 	inf->l.ttys[(inf->count)++] = sb.st_rdev;
734 	return (1);
735 }
736 
737 static int
738 addelem_uid(struct listinfo *inf, const char *elem)
739 {
740 	struct passwd *pwd;
741 	char *endp;
742 	u_long bigtemp;
743 
744 	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
745 		if (*elem == '\0')
746 			warnx("Invalid (zero-length) %s name", inf->lname);
747 		else
748 			warnx("%s name too long: %s", inf->lname, elem);
749 		optfatal = 1;
750 		return (0);		/* Do not add this value. */
751 	}
752 
753 	pwd = getpwnam(elem);
754 	if (pwd == NULL) {
755 		errno = 0;
756 		bigtemp = strtoul(elem, &endp, 10);
757 		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
758 			warnx("No %s named '%s'", inf->lname, elem);
759 		else {
760 			/* The string is all digits, so it might be a userID. */
761 			pwd = getpwuid((uid_t)bigtemp);
762 			if (pwd == NULL)
763 				warnx("No %s name or ID matches '%s'",
764 				    inf->lname, elem);
765 		}
766 	}
767 	if (pwd == NULL) {
768 		/*
769 		 * These used to be treated as minor warnings (and the
770 		 * option was simply ignored), but now they are fatal
771 		 * errors (and the command will be aborted).
772 		 */
773 		optfatal = 1;
774 		return (0);		/* Do not add this value. */
775 	}
776 
777 	if (inf->count >= inf->maxcount)
778 		expand_list(inf);
779 	inf->l.uids[(inf->count)++] = pwd->pw_uid;
780 	return (1);
781 }
782 
783 static void
784 add_list(struct listinfo *inf, const char *argp)
785 {
786 	const char *savep;
787 	char *cp, *endp;
788 	int toolong;
789 	char elemcopy[PATH_MAX];
790 
791 	while (*argp != '\0') {
792 		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
793 			argp++;
794 		savep = argp;
795 		toolong = 0;
796 		cp = elemcopy;
797 		if (strchr(T_SEP, *argp) == NULL) {
798 			endp = elemcopy + sizeof(elemcopy) - 1;
799 			while (*argp != '\0' && cp <= endp &&
800 			    strchr(W_SEP T_SEP, *argp) == NULL)
801 				*cp++ = *argp++;
802 			if (cp > endp)
803 				toolong = 1;
804 		}
805 		if (!toolong) {
806 			*cp = '\0';
807 #ifndef ADD_PS_LISTRESET
808 			/*
809 			 * This is how the standard expects lists to
810 			 * be handled.
811 			 */
812 			inf->addelem(inf, elemcopy);
813 #else
814 			/*-
815 			 * This would add a simple non-standard-but-convienent
816 			 * feature.
817 			 *
818 			 * XXX - The first time I tried to add this check,
819 			 *	it increased the total size of `ps' by 3940
820 			 *	bytes on i386!  That's 12% of the entire
821 			 *	program!  The `ps.o' file grew by only about
822 			 *	40 bytes, but the final (stripped) executable
823 			 *	in /bin/ps grew by 12%.  I have not had time
824 			 *	to investigate, so skip the feature for now.
825 			 */
826 			/*
827 			 * We now have a single element.  Add it to the
828 			 * list, unless the element is ":".  In that case,
829 			 * reset the list so previous entries are ignored.
830 			 */
831 			if (strcmp(elemcopy, ":") == 0)
832 				inf->count = 0;
833 			else
834 				inf->addelem(inf, elemcopy);
835 #endif
836 		} else {
837 			/*
838 			 * The string is too long to copy.  Find the end
839 			 * of the string to print out the warning message.
840 			 */
841 			while (*argp != '\0' && strchr(W_SEP T_SEP,
842 			    *argp) == NULL)
843 				argp++;
844 			warnx("Value too long: %.*s", (int)(argp - savep),
845 			    savep);
846 			optfatal = 1;
847 		}
848 		/*
849 		 * Skip over any number of trailing whitespace characters,
850 		 * but only one (at most) trailing element-terminating
851 		 * character.
852 		 */
853 		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
854 			argp++;
855 		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
856 			argp++;
857 			/* Catch case where string ended with a comma. */
858 			if (*argp == '\0')
859 				inf->addelem(inf, argp);
860 		}
861 	}
862 }
863 
864 static void *
865 expand_list(struct listinfo *inf)
866 {
867 	void *newlist;
868 	int newmax;
869 
870 	newmax = (inf->maxcount + 1) << 1;
871 	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
872 	if (newlist == NULL) {
873 		free(inf->l.ptr);
874 		errx(1, "realloc to %d %ss failed", newmax,
875 		    inf->lname);
876 	}
877 	inf->maxcount = newmax;
878 	inf->l.ptr = newlist;
879 
880 	return (newlist);
881 }
882 
883 static void
884 free_list(struct listinfo *inf)
885 {
886 
887 	inf->count = inf->elemsize = inf->maxcount = 0;
888 	if (inf->l.ptr != NULL)
889 		free(inf->l.ptr);
890 	inf->addelem = NULL;
891 	inf->lname = NULL;
892 	inf->l.ptr = NULL;
893 }
894 
895 static void
896 init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
897     const char *lname)
898 {
899 
900 	inf->count = inf->maxcount = 0;
901 	inf->elemsize = elemsize;
902 	inf->addelem = artn;
903 	inf->lname = lname;
904 	inf->l.ptr = NULL;
905 }
906 
907 VARENT *
908 find_varentry(VAR *v)
909 {
910 	struct varent *vent;
911 
912 	for (vent = vhead; vent; vent = vent->next) {
913 		if (strcmp(vent->var->name, v->name) == 0)
914 			return vent;
915 	}
916 	return NULL;
917 }
918 
919 static void
920 scanvars(void)
921 {
922 	struct varent *vent;
923 	VAR *v;
924 
925 	for (vent = vhead; vent; vent = vent->next) {
926 		v = vent->var;
927 		if (v->flag & DSIZ) {
928 			v->dwidth = v->width;
929 			v->width = 0;
930 		}
931 		if (v->flag & USER)
932 			needuser = 1;
933 		if (v->flag & COMM)
934 			needcomm = 1;
935 	}
936 }
937 
938 static void
939 dynsizevars(KINFO *ki)
940 {
941 	struct varent *vent;
942 	VAR *v;
943 	int i;
944 
945 	for (vent = vhead; vent; vent = vent->next) {
946 		v = vent->var;
947 		if (!(v->flag & DSIZ))
948 			continue;
949 		i = (v->sproc)( ki);
950 		if (v->width < i)
951 			v->width = i;
952 		if (v->width > v->dwidth)
953 			v->width = v->dwidth;
954 	}
955 }
956 
957 static void
958 sizevars(void)
959 {
960 	struct varent *vent;
961 	VAR *v;
962 	int i;
963 
964 	for (vent = vhead; vent; vent = vent->next) {
965 		v = vent->var;
966 		i = strlen(vent->header);
967 		if (v->width < i)
968 			v->width = i;
969 		totwidth += v->width + 1;	/* +1 for space */
970 	}
971 	totwidth--;
972 }
973 
974 static const char *
975 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
976     char *comm, int maxlen)
977 {
978 	const char *s;
979 
980 	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
981 	return (s);
982 }
983 
984 #define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
985 
986 static void
987 saveuser(KINFO *ki)
988 {
989 
990 	if (ki->ki_p->ki_sflag & PS_INMEM) {
991 		/*
992 		 * The u-area might be swapped out, and we can't get
993 		 * at it because we have a crashdump and no swap.
994 		 * If it's here fill in these fields, otherwise, just
995 		 * leave them 0.
996 		 */
997 		ki->ki_valid = 1;
998 	} else
999 		ki->ki_valid = 0;
1000 	/*
1001 	 * save arguments if needed
1002 	 */
1003 	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
1004 		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
1005 		    MAXCOMLEN));
1006 	} else if (needcomm) {
1007 		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
1008 	} else {
1009 		ki->ki_args = NULL;
1010 	}
1011 	if (needenv && UREADOK(ki)) {
1012 		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
1013 	} else if (needenv) {
1014 		ki->ki_env = malloc(3);
1015 		strcpy(ki->ki_env, "()");
1016 	} else {
1017 		ki->ki_env = NULL;
1018 	}
1019 }
1020 
1021 static int
1022 pscomp(const void *a, const void *b)
1023 {
1024 	const KINFO *ka, *kb;
1025 	double cpua, cpub;
1026 	segsz_t sizea, sizeb;
1027 
1028 	ka = a;
1029 	kb = b;
1030 	/* SORTCPU and SORTMEM are sorted in descending order. */
1031 	if (sortby == SORTCPU) {
1032 		cpua = getpcpu(ka);
1033 		cpub = getpcpu(kb);
1034 		if (cpua < cpub)
1035 			return (1);
1036 		if (cpua > cpub)
1037 			return (-1);
1038 	}
1039 	if (sortby == SORTMEM) {
1040 		sizea = ka->ki_p->ki_tsize + ka->ki_p->ki_dsize +
1041 		    ka->ki_p->ki_ssize;
1042 		sizeb = kb->ki_p->ki_tsize + kb->ki_p->ki_dsize +
1043 		    kb->ki_p->ki_ssize;
1044 		if (sizea < sizeb)
1045 			return (1);
1046 		if (sizea > sizeb)
1047 			return (-1);
1048 	}
1049 	/*
1050 	 * TTY's are sorted in ascending order, except that all NODEV
1051 	 * processes come before all processes with a device.
1052 	 */
1053 	if (ka->ki_p->ki_tdev == NODEV && kb->ki_p->ki_tdev != NODEV)
1054 		return (-1);
1055 	if (ka->ki_p->ki_tdev != NODEV && kb->ki_p->ki_tdev == NODEV)
1056 		return (1);
1057 	if (ka->ki_p->ki_tdev < kb->ki_p->ki_tdev)
1058 		return (-1);
1059 	if (ka->ki_p->ki_tdev > kb->ki_p->ki_tdev)
1060 		return (1);
1061 	/* PID's are sorted in ascending order. */
1062 	if (ka->ki_p->ki_pid < kb->ki_p->ki_pid)
1063 		return (-1);
1064 	if (ka->ki_p->ki_pid > kb->ki_p->ki_pid)
1065 		return (1);
1066 	return (0);
1067 }
1068 
1069 /*
1070  * ICK (all for getopt), would rather hide the ugliness
1071  * here than taint the main code.
1072  *
1073  *  ps foo -> ps -foo
1074  *  ps 34 -> ps -p34
1075  *
1076  * The old convention that 't' with no trailing tty arg means the users
1077  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1078  * feature is available with the option 'T', which takes no argument.
1079  */
1080 static char *
1081 kludge_oldps_options(char *s)
1082 {
1083 	int have_fmt;
1084 	size_t len;
1085 	char *newopts, *ns, *cp;
1086 
1087 	/*
1088 	 * If we have an 'o' option, then note it, since we don't want to do
1089 	 * some types of munging.
1090 	 */
1091 	have_fmt = index(s, 'o') != NULL;
1092 
1093 	len = strlen(s);
1094 	if ((newopts = ns = malloc(len + 2)) == NULL)
1095 		errx(1, "malloc failed");
1096 	/*
1097 	 * options begin with '-'
1098 	 */
1099 	if (*s != '-')
1100 		*ns++ = '-';	/* add option flag */
1101 	/*
1102 	 * gaze to end of argv[1]
1103 	 */
1104 	cp = s + len - 1;
1105 	/*
1106 	 * if last letter is a 't' flag with no argument (in the context
1107 	 * of the oldps options -- option string NOT starting with a '-' --
1108 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1109 	 *
1110 	 * However, if a flag accepting a string argument is found in the
1111 	 * option string, the remainder of the string is the argument to
1112 	 * that flag; do not modify that argument.
1113 	 */
1114 	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
1115 		*cp = 'T';
1116 	else {
1117 		/*
1118 		 * otherwise check for trailing number, which *may* be a
1119 		 * pid.
1120 		 */
1121 		while (cp >= s && isdigit(*cp))
1122 			--cp;
1123 	}
1124 	cp++;
1125 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
1126 	ns += cp - s;
1127 	/*
1128 	 * if there's a trailing number, and not a preceding 'p' (pid) or
1129 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
1130 	 */
1131 	if (isdigit(*cp) &&
1132 	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
1133 	    (cp - 1 == s || cp[-2] != 't') && !have_fmt)
1134 		*ns++ = 'p';
1135 	(void)strcpy(ns, cp);		/* and append the number */
1136 
1137 	return (newopts);
1138 }
1139 
1140 static void
1141 usage(void)
1142 {
1143 #define	SINGLE_OPTS	"[-aC" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1144 
1145 	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1146 	    "usage: ps " SINGLE_OPTS " [-G gid[,gid]] [-O|o fmt]",
1147 	    "          [-p pid[,pid]] [-t tty[,tty]] [-U user[,user]]",
1148 	    "          [-M core] [-N system]",
1149 	    "       ps [-L]");
1150 	exit(1);
1151 }
1152