ps.c revision 129917
11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1990, 1993, 1994
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * Redistribution and use in source and binary forms, with or without
61556Srgrimes * modification, are permitted provided that the following conditions
71556Srgrimes * are met:
81556Srgrimes * 1. Redistributions of source code must retain the above copyright
91556Srgrimes *    notice, this list of conditions and the following disclaimer.
101556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111556Srgrimes *    notice, this list of conditions and the following disclaimer in the
121556Srgrimes *    documentation and/or other materials provided with the distribution.
131556Srgrimes * 4. Neither the name of the University nor the names of its contributors
141556Srgrimes *    may be used to endorse or promote products derived from this software
151556Srgrimes *    without specific prior written permission.
161556Srgrimes *
171556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
181556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
191556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
201556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
211556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
221556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
231556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
241556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
251556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
261556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
271556Srgrimes * SUCH DAMAGE.
28127499Sgad * ------+---------+---------+-------- + --------+---------+---------+---------*
29127499Sgad * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
30127499Sgad * All rights reserved.
31127499Sgad *
32127499Sgad * Significant modifications made to bring `ps' options somewhat closer
33127499Sgad * to the standard for `ps' as described in SingleUnixSpec-v3.
34127499Sgad * ------+---------+---------+-------- + --------+---------+---------+---------*
351556Srgrimes */
361556Srgrimes
371556Srgrimes#ifndef lint
3890143Smarkmstatic const char copyright[] =
391556Srgrimes"@(#) Copyright (c) 1990, 1993, 1994\n\
401556Srgrimes	The Regents of the University of California.  All rights reserved.\n";
411556Srgrimes#endif /* not lint */
421556Srgrimes
4390143Smarkm#if 0
441556Srgrimes#ifndef lint
4536049Scharnierstatic char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
4690143Smarkm#endif /* not lint */
4736049Scharnier#endif
48110391Scharnier
4999110Sobrien#include <sys/cdefs.h>
5099110Sobrien__FBSDID("$FreeBSD: head/bin/ps/ps.c 129917 2004-06-01 03:01:51Z gad $");
511556Srgrimes
521556Srgrimes#include <sys/param.h>
53127546Sgad#include <sys/proc.h>
543296Sdg#include <sys/user.h>
551556Srgrimes#include <sys/stat.h>
561556Srgrimes#include <sys/ioctl.h>
571556Srgrimes#include <sys/sysctl.h>
581556Srgrimes
591556Srgrimes#include <ctype.h>
601556Srgrimes#include <err.h>
61127149Sgad#include <errno.h>
621556Srgrimes#include <fcntl.h>
63127499Sgad#include <grp.h>
641556Srgrimes#include <kvm.h>
6513514Smpp#include <limits.h>
6673367Sache#include <locale.h>
671556Srgrimes#include <paths.h>
6890143Smarkm#include <pwd.h>
691556Srgrimes#include <stdio.h>
701556Srgrimes#include <stdlib.h>
711556Srgrimes#include <string.h>
721556Srgrimes#include <unistd.h>
731556Srgrimes
741556Srgrimes#include "ps.h"
751556Srgrimes
76127499Sgad#define	W_SEP	" \t"		/* "Whitespace" list separators */
77127499Sgad#define	T_SEP	","		/* "Terminate-element" list separators */
7866377Sbrian
79127537Sgad#ifdef LAZY_PS
80127555Sgad#define	DEF_UREAD	0
81127537Sgad#define	OPT_LAZY_f	"f"
82127537Sgad#else
83127555Sgad#define	DEF_UREAD	1	/* Always do the more-expensive read. */
84127537Sgad#define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
85127537Sgad#endif
86127537Sgad
87129914Sgad/*
88129914Sgad * isdigit is defined to work on an 'int', in the range 0 to 255, plus EOF.
89129914Sgad * Define a wrapper which can take 'char', either signed or unsigned.
90129914Sgad */
91129914Sgad#define	isdigitch(Anychar) isdigit(((int) Anychar) & 255)
92129914Sgad
93127537Sgadint	 cflag;			/* -c */
94127537Sgadint	 eval;			/* Exit value */
95127537Sgadtime_t	 now;			/* Current time(3) value */
96127537Sgadint	 rawcpu;		/* -C */
97127537Sgadint	 sumrusage;		/* -S */
98127537Sgadint	 termwidth;		/* Width of the screen (0 == infinity). */
99127537Sgadint	 totwidth;		/* Calculated-width of requested variables. */
100127537Sgad
10190143Smarkmstruct varent *vhead;
1021556Srgrimes
103127537Sgadstatic int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
104127537Sgadstatic kvm_t	*kd;
105127537Sgadstatic KINFO	*kinfo;
106127537Sgadstatic int	 needcomm;	/* -o "command" */
107127537Sgadstatic int	 needenv;	/* -e */
108127537Sgadstatic int	 needuser;	/* -o "user" */
109127537Sgadstatic int	 optfatal;	/* Fatal error parsing some list-option. */
1101556Srgrimes
111127537Sgadstatic enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
11297966Sjmallett
113127499Sgadstruct listinfo;
114127537Sgadtypedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
115127499Sgad
116127499Sgadstruct listinfo {
117127499Sgad	int		 count;
118127499Sgad	int		 maxcount;
119127499Sgad	int		 elemsize;
120127499Sgad	addelem_rtn	*addelem;
121127499Sgad	const char	*lname;
122127499Sgad	union {
123127499Sgad		gid_t	*gids;
124127499Sgad		pid_t	*pids;
125127499Sgad		dev_t	*ttys;
126127499Sgad		uid_t	*uids;
127127499Sgad		void	*ptr;
128127823Sgad	} l;
129127499Sgad};
130127499Sgad
131127499Sgadstatic int	 addelem_gid(struct listinfo *, const char *);
132127499Sgadstatic int	 addelem_pid(struct listinfo *, const char *);
133127499Sgadstatic int	 addelem_tty(struct listinfo *, const char *);
134127499Sgadstatic int	 addelem_uid(struct listinfo *, const char *);
135127499Sgadstatic void	 add_list(struct listinfo *, const char *);
136127536Sgadstatic void	 dynsizevars(KINFO *);
137127499Sgadstatic void	*expand_list(struct listinfo *);
138127598Sgadstatic const char *
139127598Sgad		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
140127536Sgad		    KINFO *, char *, int);
141127499Sgadstatic void	 free_list(struct listinfo *);
142127499Sgadstatic void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
143129915Sgadstatic char	*kludge_oldps_options(const char *opts, char *, const char *);
144127536Sgadstatic int	 pscomp(const void *, const void *);
145127536Sgadstatic void	 saveuser(KINFO *);
146127536Sgadstatic void	 scanvars(void);
147127536Sgadstatic void	 sizevars(void);
148127536Sgadstatic void	 usage(void);
149127499Sgad
15097875Sjmallettstatic char dfmt[] = "pid,tt,state,time,command";
151129635Sgadstatic char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
152127538Sgadstatic char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
153127538Sgad			"tt,time,command";
15490143Smarkmstatic char   o1[] = "pid";
15597875Sjmallettstatic char   o2[] = "tt,state,time,command";
15697875Sjmallettstatic char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
157127538Sgadstatic char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
158127538Sgad			"%cpu,%mem,command";
159105831Srwatsonstatic char Zfmt[] = "label";
1601556Srgrimes
161127843Sgad#define	PS_ARGS	"AaCce" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
16298494Ssobomax
1631556Srgrimesint
16490110Simpmain(int argc, char *argv[])
1651556Srgrimes{
166127499Sgad	struct listinfo gidlist, pgrplist, pidlist;
167127499Sgad	struct listinfo ruidlist, sesslist, ttylist, uidlist;
1681556Srgrimes	struct kinfo_proc *kp;
1691556Srgrimes	struct varent *vent;
1701556Srgrimes	struct winsize ws;
171129914Sgad	const char *nlistf, *memf;
172127539Sgad	char *cols;
173127499Sgad	int all, ch, dropgid, elem, flag, _fmt, i, lineno;
174129914Sgad	int nentries, nkept, nselectors;
175127499Sgad	int prtheader, showthreads, wflag, what, xkeep, xkeep_implied;
17690143Smarkm	char errbuf[_POSIX2_LINE_MAX];
1771556Srgrimes
17811809Sache	(void) setlocale(LC_ALL, "");
179127542Sgad	time(&now);			/* Used by routines in print.c. */
18011809Sache
18197804Stjr	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
18297804Stjr		termwidth = atoi(cols);
18397804Stjr	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1841556Srgrimes	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1851556Srgrimes	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
1861556Srgrimes	     ws.ws_col == 0)
1871556Srgrimes		termwidth = 79;
1881556Srgrimes	else
1891556Srgrimes		termwidth = ws.ws_col - 1;
1901556Srgrimes
19198494Ssobomax	/*
192129914Sgad	 * Hide a number of option-processing kludges in a separate routine,
193129914Sgad	 * to support some historical BSD behaviors, such as `ps axu'.
19498494Ssobomax	 */
195129914Sgad	if (argc > 1)
196129915Sgad		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
1971556Srgrimes
198127542Sgad	all = dropgid = _fmt = nselectors = optfatal = 0;
199127542Sgad	prtheader = showthreads = wflag = xkeep_implied = 0;
200127542Sgad	xkeep = -1;			/* Neither -x nor -X. */
201127499Sgad	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
202127499Sgad	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
203127499Sgad	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
204127499Sgad	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
205127499Sgad	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
206127499Sgad	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
207127499Sgad	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
20889909Sru	memf = nlistf = _PATH_DEVNULL;
20998494Ssobomax	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
2101556Srgrimes		switch((char)ch) {
211127499Sgad		case 'A':
212127499Sgad			/*
213127499Sgad			 * Exactly the same as `-ax'.   This has been
214127499Sgad			 * added for compatability with SUSv3, but for
215127499Sgad			 * now it will not be described in the man page.
216127499Sgad			 */
217127499Sgad			nselectors++;
218127499Sgad			all = xkeep = 1;
219127499Sgad			break;
2201556Srgrimes		case 'a':
221127499Sgad			nselectors++;
2221556Srgrimes			all = 1;
2231556Srgrimes			break;
22419068Speter		case 'C':
22519068Speter			rawcpu = 1;
22619068Speter			break;
22719068Speter		case 'c':
22819068Speter			cflag = 1;
22919068Speter			break;
2301556Srgrimes		case 'e':			/* XXX set ufmt */
2311556Srgrimes			needenv = 1;
2321556Srgrimes			break;
233127506Sgad#ifdef LAZY_PS
234127506Sgad		case 'f':
235127506Sgad			if (getuid() == 0 || getgid() == 0)
236127542Sgad				forceuread = 1;
237127506Sgad			break;
238127506Sgad#endif
239127499Sgad		case 'G':
240127499Sgad			add_list(&gidlist, optarg);
241127499Sgad			xkeep_implied = 1;
242127499Sgad			nselectors++;
243127499Sgad			break;
244127542Sgad		case 'g':
245127499Sgad#if 0
246127597Sgad			/*-
247127542Sgad			 * XXX - This SUSv3 behavior is still under debate
248127542Sgad			 *	since it conflicts with the (undocumented)
249127542Sgad			 *	`-g' option.  So we skip it for now.
250127542Sgad			 */
251127499Sgad			add_list(&pgrplist, optarg);
252127499Sgad			xkeep_implied = 1;
253127499Sgad			nselectors++;
254127499Sgad			break;
255127499Sgad#else
256127542Sgad			/* The historical BSD-ish (from SunOS) behavior. */
2571556Srgrimes			break;			/* no-op */
258127499Sgad#endif
259116265Sscottl		case 'H':
260126127Sdeischen			showthreads = KERN_PROC_INC_THREAD;
261116265Sscottl			break;
2621556Srgrimes		case 'h':
2631556Srgrimes			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
2641556Srgrimes			break;
2651556Srgrimes		case 'j':
266109502Sjmallett			parsefmt(jfmt, 0);
26790143Smarkm			_fmt = 1;
2681556Srgrimes			jfmt[0] = '\0';
2691556Srgrimes			break;
2701556Srgrimes		case 'L':
2711556Srgrimes			showkey();
2721556Srgrimes			exit(0);
2731556Srgrimes		case 'l':
274109502Sjmallett			parsefmt(lfmt, 0);
27590143Smarkm			_fmt = 1;
2761556Srgrimes			lfmt[0] = '\0';
2771556Srgrimes			break;
2781556Srgrimes		case 'M':
2791556Srgrimes			memf = optarg;
28037317Sphk			dropgid = 1;
2811556Srgrimes			break;
2821556Srgrimes		case 'm':
2831556Srgrimes			sortby = SORTMEM;
2841556Srgrimes			break;
2851556Srgrimes		case 'N':
2861556Srgrimes			nlistf = optarg;
28737317Sphk			dropgid = 1;
2881556Srgrimes			break;
2891556Srgrimes		case 'O':
290109502Sjmallett			parsefmt(o1, 1);
291109502Sjmallett			parsefmt(optarg, 1);
292109502Sjmallett			parsefmt(o2, 1);
2931556Srgrimes			o1[0] = o2[0] = '\0';
29490143Smarkm			_fmt = 1;
2951556Srgrimes			break;
2961556Srgrimes		case 'o':
297109502Sjmallett			parsefmt(optarg, 1);
29890143Smarkm			_fmt = 1;
2991556Srgrimes			break;
3001556Srgrimes		case 'p':
301127499Sgad			add_list(&pidlist, optarg);
302127499Sgad			/*
303127499Sgad			 * Note: `-p' does not *set* xkeep, but any values
304127499Sgad			 * from pidlist are checked before xkeep is.  That
305127499Sgad			 * way they are always matched, even if the user
306127499Sgad			 * specifies `-X'.
307127499Sgad			 */
308127499Sgad			nselectors++;
3091556Srgrimes			break;
310127499Sgad#if 0
311127499Sgad		case 'R':
312127597Sgad			/*-
313127542Sgad			 * XXX - This un-standard option is still under
314127542Sgad			 *	debate.  This is what SUSv3 defines as
315127542Sgad			 *	the `-U' option, and while it would be
316127542Sgad			 *	nice to have, it could cause even more
317127542Sgad			 *	confusion to implement it as `-R'.
318127542Sgad			 */
319127499Sgad			add_list(&ruidlist, optarg);
320127499Sgad			xkeep_implied = 1;
321127499Sgad			nselectors++;
322127499Sgad			break;
323127499Sgad#endif
3241556Srgrimes		case 'r':
3251556Srgrimes			sortby = SORTCPU;
3261556Srgrimes			break;
3271556Srgrimes		case 'S':
3281556Srgrimes			sumrusage = 1;
3291556Srgrimes			break;
330127499Sgad#if 0
331127499Sgad		case 's':
332127597Sgad			/*-
333127542Sgad			 * XXX - This non-standard option is still under
334127542Sgad			 *	debate.  This *is* supported on Solaris,
335127542Sgad			 *	Linux, and IRIX, but conflicts with `-s'
336127542Sgad			 *	on NetBSD and maybe some older BSD's.
337127542Sgad			 */
338127499Sgad			add_list(&sesslist, optarg);
339127499Sgad			xkeep_implied = 1;
340127499Sgad			nselectors++;
341127499Sgad			break;
342127499Sgad#endif
3431556Srgrimes		case 'T':
3441556Srgrimes			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
3451556Srgrimes				errx(1, "stdin: not a terminal");
3461556Srgrimes			/* FALLTHROUGH */
347127499Sgad		case 't':
348127499Sgad			add_list(&ttylist, optarg);
349127499Sgad			xkeep_implied = 1;
350127499Sgad			nselectors++;
3511556Srgrimes			break;
35213020Speter		case 'U':
353127499Sgad			/* This is what SUSv3 defines as the `-u' option. */
354127499Sgad			add_list(&uidlist, optarg);
355127499Sgad			xkeep_implied = 1;
356127499Sgad			nselectors++;
35713020Speter			break;
3581556Srgrimes		case 'u':
359109502Sjmallett			parsefmt(ufmt, 0);
3601556Srgrimes			sortby = SORTCPU;
36190143Smarkm			_fmt = 1;
3621556Srgrimes			ufmt[0] = '\0';
3631556Srgrimes			break;
3641556Srgrimes		case 'v':
365109502Sjmallett			parsefmt(vfmt, 0);
3661556Srgrimes			sortby = SORTMEM;
36790143Smarkm			_fmt = 1;
3681556Srgrimes			vfmt[0] = '\0';
3691556Srgrimes			break;
3701556Srgrimes		case 'w':
3711556Srgrimes			if (wflag)
3721556Srgrimes				termwidth = UNLIMITED;
3731556Srgrimes			else if (termwidth < 131)
3741556Srgrimes				termwidth = 131;
3751556Srgrimes			wflag++;
3761556Srgrimes			break;
377127499Sgad		case 'X':
378127499Sgad			/*
379127499Sgad			 * Note that `-X' and `-x' are not standard "selector"
380127499Sgad			 * options. For most selector-options, we check *all*
381127499Sgad			 * processes to see if any are matched by the given
382127499Sgad			 * value(s).  After we have a set of all the matched
383127499Sgad			 * processes, then `-X' and `-x' govern whether we
384127499Sgad			 * modify that *matched* set for processes which do
385127499Sgad			 * not have a controlling terminal.  `-X' causes
386127499Sgad			 * those processes to be deleted from the matched
387127499Sgad			 * set, while `-x' causes them to be kept.
388127499Sgad			 */
389127499Sgad			xkeep = 0;
390127499Sgad			break;
3911556Srgrimes		case 'x':
392127499Sgad			xkeep = 1;
3931556Srgrimes			break;
39486922Sgreen		case 'Z':
395109502Sjmallett			parsefmt(Zfmt, 0);
39686922Sgreen			Zfmt[0] = '\0';
39786922Sgreen			break;
3981556Srgrimes		case '?':
3991556Srgrimes		default:
4001556Srgrimes			usage();
4011556Srgrimes		}
4021556Srgrimes	argc -= optind;
4031556Srgrimes	argv += optind;
404129914Sgad
405129914Sgad	/*
406129914Sgad	 * If there arguments after processing all the options, attempt
407129914Sgad	 * to treat them as a list of process ids.
408129914Sgad	 */
409129914Sgad	while (*argv) {
410129914Sgad		if (!isdigitch(**argv))
411129914Sgad			break;
412129914Sgad		add_list(&pidlist, *argv);
413129914Sgad		argv++;
414129914Sgad	}
415129914Sgad	if (*argv) {
416129914Sgad		fprintf(stderr, "%s: illegal argument: %s\n",
417129914Sgad		    getprogname(), *argv);
418129914Sgad		usage();
419129914Sgad	}
420127499Sgad	if (optfatal)
421127542Sgad		exit(1);		/* Error messages already printed. */
422127542Sgad	if (xkeep < 0)			/* Neither -X nor -x was specified. */
423127499Sgad		xkeep = xkeep_implied;
424127499Sgad
425129914Sgad
4261556Srgrimes	/*
4271556Srgrimes	 * Discard setgid privileges if not the running kernel so that bad
4281556Srgrimes	 * guys can't print interesting stuff from kernel memory.
4291556Srgrimes	 */
43037317Sphk	if (dropgid) {
4311556Srgrimes		setgid(getgid());
43237317Sphk		setuid(getuid());
43337317Sphk	}
4341556Srgrimes
43589909Sru	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
4361556Srgrimes	if (kd == 0)
4371556Srgrimes		errx(1, "%s", errbuf);
4381556Srgrimes
43990143Smarkm	if (!_fmt)
440109502Sjmallett		parsefmt(dfmt, 0);
4411556Srgrimes
442127499Sgad	if (nselectors == 0) {
443127823Sgad		uidlist.l.ptr = malloc(sizeof(uid_t));
444127823Sgad		if (uidlist.l.ptr == NULL)
44597877Sjmallett			errx(1, "malloc failed");
446127499Sgad		nselectors = 1;
447127499Sgad		uidlist.count = uidlist.maxcount = 1;
448127823Sgad		*uidlist.l.uids = getuid();
44966377Sbrian	}
4501556Srgrimes
4511556Srgrimes	/*
4521556Srgrimes	 * scan requested variables, noting what structures are needed,
45353170Skris	 * and adjusting header widths as appropriate.
4541556Srgrimes	 */
4551556Srgrimes	scanvars();
456127499Sgad
4571556Srgrimes	/*
458127499Sgad	 * Get process list.  If the user requested just one selector-
459127499Sgad	 * option, then kvm_getprocs can be asked to return just those
460127499Sgad	 * processes.  Otherwise, have it return all processes, and
461127499Sgad	 * then this routine will search that full list and select the
462127499Sgad	 * processes which match any of the user's selector-options.
4631556Srgrimes	 */
464127499Sgad	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
465127499Sgad	flag = 0;
466127499Sgad	if (nselectors == 1) {
467129600Sgad		if (gidlist.count == 1) {
468129600Sgad			what = KERN_PROC_RGID | showthreads;
469129600Sgad			flag = *gidlist.l.gids;
470129600Sgad			nselectors = 0;
471129600Sgad		} else if (pgrplist.count == 1) {
472127499Sgad			what = KERN_PROC_PGRP | showthreads;
473127823Sgad			flag = *pgrplist.l.pids;
474127499Sgad			nselectors = 0;
475127499Sgad		} else if (pidlist.count == 1) {
476127499Sgad			what = KERN_PROC_PID | showthreads;
477127823Sgad			flag = *pidlist.l.pids;
478127499Sgad			nselectors = 0;
479127499Sgad		} else if (ruidlist.count == 1) {
480127499Sgad			what = KERN_PROC_RUID | showthreads;
481127823Sgad			flag = *ruidlist.l.uids;
482127499Sgad			nselectors = 0;
483127499Sgad		} else if (sesslist.count == 1) {
484127499Sgad			what = KERN_PROC_SESSION | showthreads;
485127823Sgad			flag = *sesslist.l.pids;
486127499Sgad			nselectors = 0;
487127499Sgad		} else if (ttylist.count == 1) {
488127499Sgad			what = KERN_PROC_TTY | showthreads;
489127823Sgad			flag = *ttylist.l.ttys;
490127499Sgad			nselectors = 0;
491127499Sgad		} else if (uidlist.count == 1) {
492127499Sgad			what = KERN_PROC_UID | showthreads;
493127823Sgad			flag = *uidlist.l.uids;
494127499Sgad			nselectors = 0;
495127499Sgad		} else if (all) {
496127499Sgad			/* No need for this routine to select processes. */
497127499Sgad			nselectors = 0;
498127499Sgad		}
4991556Srgrimes	}
500126127Sdeischen
5011556Srgrimes	/*
5021556Srgrimes	 * select procs
5031556Srgrimes	 */
504127499Sgad	nentries = -1;
505127149Sgad	kp = kvm_getprocs(kd, what, flag, &nentries);
506127544Sgad	if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
5071556Srgrimes		errx(1, "%s", kvm_geterr(kd));
508127499Sgad	nkept = 0;
509127149Sgad	if (nentries > 0) {
510127149Sgad		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
511127149Sgad			errx(1, "malloc failed");
512127149Sgad		for (i = nentries; --i >= 0; ++kp) {
513127499Sgad			/*
514127499Sgad			 * If the user specified multiple selection-criteria,
515127499Sgad			 * then keep any process matched by the inclusive OR
516127499Sgad			 * of all the selection-criteria given.
517127499Sgad			 */
518127499Sgad			if (pidlist.count > 0) {
519127499Sgad				for (elem = 0; elem < pidlist.count; elem++)
520127823Sgad					if (kp->ki_pid == pidlist.l.pids[elem])
521127499Sgad						goto keepit;
522127499Sgad			}
523127499Sgad			/*
524127499Sgad			 * Note that we had to process pidlist before
525127499Sgad			 * filtering out processes which do not have
526127499Sgad			 * a controlling terminal.
527127499Sgad			 */
528127499Sgad			if (xkeep == 0) {
529127499Sgad				if ((kp->ki_tdev == NODEV ||
530127499Sgad				    (kp->ki_flag & P_CONTROLT) == 0))
531127499Sgad					continue;
532127499Sgad			}
533127499Sgad			if (nselectors == 0)
534127499Sgad				goto keepit;
535127499Sgad			if (gidlist.count > 0) {
536127499Sgad				for (elem = 0; elem < gidlist.count; elem++)
537127823Sgad					if (kp->ki_rgid == gidlist.l.gids[elem])
538127499Sgad						goto keepit;
539127499Sgad			}
540127499Sgad			if (pgrplist.count > 0) {
541127499Sgad				for (elem = 0; elem < pgrplist.count; elem++)
542127823Sgad					if (kp->ki_pgid ==
543127823Sgad					    pgrplist.l.pids[elem])
544127499Sgad						goto keepit;
545127499Sgad			}
546127499Sgad			if (ruidlist.count > 0) {
547127499Sgad				for (elem = 0; elem < ruidlist.count; elem++)
548127823Sgad					if (kp->ki_ruid ==
549127823Sgad					    ruidlist.l.uids[elem])
550127499Sgad						goto keepit;
551127499Sgad			}
552127499Sgad			if (sesslist.count > 0) {
553127499Sgad				for (elem = 0; elem < sesslist.count; elem++)
554127823Sgad					if (kp->ki_sid == sesslist.l.pids[elem])
555127499Sgad						goto keepit;
556127499Sgad			}
557127499Sgad			if (ttylist.count > 0) {
558127499Sgad				for (elem = 0; elem < ttylist.count; elem++)
559127823Sgad					if (kp->ki_tdev == ttylist.l.ttys[elem])
560127499Sgad						goto keepit;
561127499Sgad			}
562127499Sgad			if (uidlist.count > 0) {
563127499Sgad				for (elem = 0; elem < uidlist.count; elem++)
564127823Sgad					if (kp->ki_uid == uidlist.l.uids[elem])
565127499Sgad						goto keepit;
566127499Sgad			}
567127499Sgad			/*
568127499Sgad			 * This process did not match any of the user's
569127499Sgad			 * selector-options, so skip the process.
570127499Sgad			 */
571127499Sgad			continue;
572127499Sgad
573127499Sgad		keepit:
574127499Sgad			kinfo[nkept].ki_p = kp;
575127149Sgad			if (needuser)
576127499Sgad				saveuser(&kinfo[nkept]);
577127499Sgad			dynsizevars(&kinfo[nkept]);
578127499Sgad			nkept++;
579127149Sgad		}
5801556Srgrimes	}
58125271Sjkh
58225271Sjkh	sizevars();
58325271Sjkh
5841556Srgrimes	/*
5851556Srgrimes	 * print header
5861556Srgrimes	 */
5871556Srgrimes	printheader();
588127499Sgad	if (nkept == 0)
58962803Swill		exit(1);
590127499Sgad
5911556Srgrimes	/*
5921556Srgrimes	 * sort proc list
5931556Srgrimes	 */
594127499Sgad	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
5951556Srgrimes	/*
596127499Sgad	 * For each process, call each variable output function.
5971556Srgrimes	 */
598127499Sgad	for (i = lineno = 0; i < nkept; i++) {
5991556Srgrimes		for (vent = vhead; vent; vent = vent->next) {
6001556Srgrimes			(vent->var->oproc)(&kinfo[i], vent);
6011556Srgrimes			if (vent->next != NULL)
6021556Srgrimes				(void)putchar(' ');
6031556Srgrimes		}
6041556Srgrimes		(void)putchar('\n');
6051556Srgrimes		if (prtheader && lineno++ == prtheader - 4) {
6061556Srgrimes			(void)putchar('\n');
6071556Srgrimes			printheader();
6081556Srgrimes			lineno = 0;
6091556Srgrimes		}
6101556Srgrimes	}
611127499Sgad	free_list(&gidlist);
612127499Sgad	free_list(&pidlist);
613127499Sgad	free_list(&pgrplist);
614127499Sgad	free_list(&ruidlist);
615127499Sgad	free_list(&sesslist);
616127499Sgad	free_list(&ttylist);
617127499Sgad	free_list(&uidlist);
61866377Sbrian
6191556Srgrimes	exit(eval);
6201556Srgrimes}
6211556Srgrimes
622127499Sgadstatic int
623127499Sgadaddelem_gid(struct listinfo *inf, const char *elem)
624127499Sgad{
625127499Sgad	struct group *grp;
626127499Sgad	const char *nameorID;
627127499Sgad	char *endp;
628127602Sgad	u_long bigtemp;
629127499Sgad
630127499Sgad	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
631127499Sgad		if (*elem == '\0')
632127499Sgad			warnx("Invalid (zero-length) %s name", inf->lname);
633127499Sgad		else
634127499Sgad			warnx("%s name too long: %s", inf->lname, elem);
635127499Sgad		optfatal = 1;
636127542Sgad		return (0);		/* Do not add this value. */
637127499Sgad	}
638127499Sgad
639127499Sgad	/*
640127499Sgad	 * SUSv3 states that `ps -G grouplist' should match "real-group
641127499Sgad	 * ID numbers", and does not mention group-names.  I do want to
642127499Sgad	 * also support group-names, so this tries for a group-id first,
643127499Sgad	 * and only tries for a name if that doesn't work.  This is the
644127499Sgad	 * opposite order of what is done in addelem_uid(), but in
645127499Sgad	 * practice the order would only matter for group-names which
646127499Sgad	 * are all-numeric.
647127499Sgad	 */
648127499Sgad	grp = NULL;
649127499Sgad	nameorID = "named";
650127499Sgad	errno = 0;
651127602Sgad	bigtemp = strtoul(elem, &endp, 10);
652127602Sgad	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
653127499Sgad		nameorID = "name or ID matches";
654127602Sgad		grp = getgrgid((gid_t)bigtemp);
655127499Sgad	}
656127499Sgad	if (grp == NULL)
657127499Sgad		grp = getgrnam(elem);
658127499Sgad	if (grp == NULL) {
659127499Sgad		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
660127499Sgad		optfatal = 1;
661127542Sgad		return (0);		/* Do not add this value. */
662127499Sgad	}
663127499Sgad
664127499Sgad	if (inf->count >= inf->maxcount)
665127499Sgad		expand_list(inf);
666127823Sgad	inf->l.gids[(inf->count)++] = grp->gr_gid;
667127499Sgad	return (1);
668127499Sgad}
669127499Sgad
670127597Sgad#define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h. */
671127499Sgadstatic int
672127499Sgadaddelem_pid(struct listinfo *inf, const char *elem)
673127149Sgad{
674127539Sgad	char *endp;
675127149Sgad	long tempid;
676127149Sgad
677129917Sgad	if (*elem == '\0') {
678129917Sgad		warnx("Invalid (zero-length) process id");
679129917Sgad		optfatal = 1;
680129917Sgad		return (0);		/* Do not add this value. */
681129917Sgad	} else {
682127499Sgad		errno = 0;
683127499Sgad		tempid = strtol(elem, &endp, 10);
684127499Sgad		if (*endp != '\0' || tempid < 0 || elem == endp) {
685127499Sgad			warnx("Invalid %s: %s", inf->lname, elem);
686127499Sgad			errno = ERANGE;
687127499Sgad		} else if (errno != 0 || tempid > BSD_PID_MAX) {
688127499Sgad			warnx("%s too large: %s", inf->lname, elem);
689127499Sgad			errno = ERANGE;
690127149Sgad		}
691127499Sgad		if (errno == ERANGE) {
692127499Sgad			optfatal = 1;
693127542Sgad			return (0);	/* Do not add this value. */
694127149Sgad		}
695127149Sgad	}
696127149Sgad
697127499Sgad	if (inf->count >= inf->maxcount)
698127499Sgad		expand_list(inf);
699127823Sgad	inf->l.pids[(inf->count)++] = tempid;
700127499Sgad	return (1);
701127499Sgad}
702127499Sgad#undef	BSD_PID_MAX
703127149Sgad
704127499Sgadstatic int
705127499Sgadaddelem_tty(struct listinfo *inf, const char *elem)
706127499Sgad{
707127539Sgad	const char *ttypath;
708127539Sgad	struct stat sb;
709127499Sgad	char pathbuf[PATH_MAX];
710127499Sgad
711127499Sgad	if (strcmp(elem, "co") == 0)
712127499Sgad		ttypath = strdup(_PATH_CONSOLE);
713127499Sgad	else if (*elem == '/')
714127499Sgad		ttypath = elem;
715127499Sgad	else {
716127499Sgad		strlcpy(pathbuf, _PATH_TTY, sizeof(pathbuf));
717127499Sgad		strlcat(pathbuf, elem, sizeof(pathbuf));
718127499Sgad		ttypath = pathbuf;
719127499Sgad	}
720127499Sgad
721127499Sgad	if (stat(ttypath, &sb) == -1) {
722127499Sgad		warn("%s", ttypath);
723127499Sgad		optfatal = 1;
724127542Sgad		return (0);		/* Do not add this value. */
725127499Sgad	}
726127499Sgad	if (!S_ISCHR(sb.st_mode)) {
727127499Sgad		warn("%s: Not a terminal", ttypath);
728127499Sgad		optfatal = 1;
729127542Sgad		return (0);		/* Do not add this value. */
730127499Sgad	}
731127499Sgad
732127499Sgad	if (inf->count >= inf->maxcount)
733127499Sgad		expand_list(inf);
734127823Sgad	inf->l.ttys[(inf->count)++] = sb.st_rdev;
735127499Sgad	return (1);
736127149Sgad}
737127149Sgad
738127499Sgadstatic int
739127499Sgadaddelem_uid(struct listinfo *inf, const char *elem)
74066377Sbrian{
74166377Sbrian	struct passwd *pwd;
742127539Sgad	char *endp;
743127602Sgad	u_long bigtemp;
74466377Sbrian
745127499Sgad	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
746127499Sgad		if (*elem == '\0')
747127499Sgad			warnx("Invalid (zero-length) %s name", inf->lname);
748127499Sgad		else
749127499Sgad			warnx("%s name too long: %s", inf->lname, elem);
750127499Sgad		optfatal = 1;
751127542Sgad		return (0);		/* Do not add this value. */
752127499Sgad	}
75366377Sbrian
754127499Sgad	pwd = getpwnam(elem);
755127499Sgad	if (pwd == NULL) {
756127499Sgad		errno = 0;
757127602Sgad		bigtemp = strtoul(elem, &endp, 10);
758127602Sgad		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
759127499Sgad			warnx("No %s named '%s'", inf->lname, elem);
760127499Sgad		else {
761127499Sgad			/* The string is all digits, so it might be a userID. */
762127602Sgad			pwd = getpwuid((uid_t)bigtemp);
763127499Sgad			if (pwd == NULL)
764127499Sgad				warnx("No %s name or ID matches '%s'",
765127499Sgad				    inf->lname, elem);
76666377Sbrian		}
767127499Sgad	}
768127499Sgad	if (pwd == NULL) {
769127509Sgad		/*
770127509Sgad		 * These used to be treated as minor warnings (and the
771127509Sgad		 * option was simply ignored), but now they are fatal
772127509Sgad		 * errors (and the command will be aborted).
773127509Sgad		 */
774127509Sgad		optfatal = 1;
775127542Sgad		return (0);		/* Do not add this value. */
776127499Sgad	}
777127499Sgad
778127499Sgad	if (inf->count >= inf->maxcount)
779127499Sgad		expand_list(inf);
780127823Sgad	inf->l.uids[(inf->count)++] = pwd->pw_uid;
781127499Sgad	return (1);
782127499Sgad}
783127499Sgad
784127499Sgadstatic void
785127499Sgadadd_list(struct listinfo *inf, const char *argp)
786127499Sgad{
787127499Sgad	const char *savep;
788127499Sgad	char *cp, *endp;
789127499Sgad	int toolong;
790127539Sgad	char elemcopy[PATH_MAX];
791127499Sgad
792129917Sgad	if (*argp == 0)
793129917Sgad		    inf->addelem(inf, elemcopy);
794129917Sgad
795127499Sgad	while (*argp != '\0') {
796127499Sgad		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
797127499Sgad			argp++;
798127499Sgad		savep = argp;
799127499Sgad		toolong = 0;
800127499Sgad		cp = elemcopy;
801127499Sgad		if (strchr(T_SEP, *argp) == NULL) {
802127499Sgad			endp = elemcopy + sizeof(elemcopy) - 1;
803127499Sgad			while (*argp != '\0' && cp <= endp &&
804127499Sgad			    strchr(W_SEP T_SEP, *argp) == NULL)
805127499Sgad				*cp++ = *argp++;
806127499Sgad			if (cp > endp)
807127499Sgad				toolong = 1;
80866377Sbrian		}
809127499Sgad		if (!toolong) {
810127499Sgad			*cp = '\0';
811127499Sgad#ifndef ADD_PS_LISTRESET
812127542Sgad			/*
813127542Sgad			 * This is how the standard expects lists to
814127542Sgad			 * be handled.
815127542Sgad			 */
816127499Sgad			inf->addelem(inf, elemcopy);
817127499Sgad#else
818127597Sgad			/*-
819127542Sgad			 * This would add a simple non-standard-but-convienent
820127542Sgad			 * feature.
821127542Sgad			 *
822127542Sgad			 * XXX - The first time I tried to add this check,
823127542Sgad			 *	it increased the total size of `ps' by 3940
824127542Sgad			 *	bytes on i386!  That's 12% of the entire
825127542Sgad			 *	program!  The `ps.o' file grew by only about
826127542Sgad			 *	40 bytes, but the final (stripped) executable
827127542Sgad			 *	in /bin/ps grew by 12%.  I have not had time
828127542Sgad			 *	to investigate, so skip the feature for now.
829127542Sgad			 */
830127542Sgad			/*
831127499Sgad			 * We now have a single element.  Add it to the
832127499Sgad			 * list, unless the element is ":".  In that case,
833127499Sgad			 * reset the list so previous entries are ignored.
834127499Sgad			 */
835127499Sgad			if (strcmp(elemcopy, ":") == 0)
836127499Sgad				inf->count = 0;
837127499Sgad			else
838127499Sgad				inf->addelem(inf, elemcopy);
839127499Sgad#endif
840127499Sgad		} else {
841127499Sgad			/*
842127499Sgad			 * The string is too long to copy.  Find the end
843127499Sgad			 * of the string to print out the warning message.
844127499Sgad			 */
845127499Sgad			while (*argp != '\0' && strchr(W_SEP T_SEP,
846127499Sgad			    *argp) == NULL)
847127499Sgad				argp++;
848127499Sgad			warnx("Value too long: %.*s", (int)(argp - savep),
849127499Sgad			    savep);
850127499Sgad			optfatal = 1;
85166377Sbrian		}
852127499Sgad		/*
853127499Sgad		 * Skip over any number of trailing whitespace characters,
854127499Sgad		 * but only one (at most) trailing element-terminating
855127499Sgad		 * character.
856127499Sgad		 */
857127499Sgad		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
858127499Sgad			argp++;
859127499Sgad		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
860127499Sgad			argp++;
861127499Sgad			/* Catch case where string ended with a comma. */
862127499Sgad			if (*argp == '\0')
863127499Sgad				inf->addelem(inf, argp);
864127499Sgad		}
86566377Sbrian	}
866127499Sgad}
86766377Sbrian
868127499Sgadstatic void *
869127499Sgadexpand_list(struct listinfo *inf)
870127499Sgad{
871127539Sgad	void *newlist;
872127499Sgad	int newmax;
87366377Sbrian
874127499Sgad	newmax = (inf->maxcount + 1) << 1;
875127823Sgad	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
876127499Sgad	if (newlist == NULL) {
877127823Sgad		free(inf->l.ptr);
878127499Sgad		errx(1, "realloc to %d %ss failed", newmax,
879127499Sgad		    inf->lname);
880127499Sgad	}
881127499Sgad	inf->maxcount = newmax;
882127823Sgad	inf->l.ptr = newlist;
883127499Sgad
884127499Sgad	return (newlist);
88566377Sbrian}
88666377Sbrian
887127499Sgadstatic void
888127499Sgadfree_list(struct listinfo *inf)
889127499Sgad{
890127499Sgad
891127499Sgad	inf->count = inf->elemsize = inf->maxcount = 0;
892127823Sgad	if (inf->l.ptr != NULL)
893127823Sgad		free(inf->l.ptr);
894127499Sgad	inf->addelem = NULL;
895127499Sgad	inf->lname = NULL;
896127823Sgad	inf->l.ptr = NULL;
897127499Sgad}
898127499Sgad
899127499Sgadstatic void
900127499Sgadinit_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
901127499Sgad    const char *lname)
902127499Sgad{
903127499Sgad
904127499Sgad	inf->count = inf->maxcount = 0;
905127499Sgad	inf->elemsize = elemsize;
906127499Sgad	inf->addelem = artn;
907127499Sgad	inf->lname = lname;
908127823Sgad	inf->l.ptr = NULL;
909127499Sgad}
910127499Sgad
911109502SjmallettVARENT *
912109502Sjmallettfind_varentry(VAR *v)
913109502Sjmallett{
914109502Sjmallett	struct varent *vent;
915109502Sjmallett
916109502Sjmallett	for (vent = vhead; vent; vent = vent->next) {
917109502Sjmallett		if (strcmp(vent->var->name, v->name) == 0)
918109502Sjmallett			return vent;
919109502Sjmallett	}
920109502Sjmallett	return NULL;
921109502Sjmallett}
922109502Sjmallett
9231556Srgrimesstatic void
92490110Simpscanvars(void)
9251556Srgrimes{
9261556Srgrimes	struct varent *vent;
9271556Srgrimes	VAR *v;
92825271Sjkh
92925271Sjkh	for (vent = vhead; vent; vent = vent->next) {
93025271Sjkh		v = vent->var;
93125271Sjkh		if (v->flag & DSIZ) {
93225271Sjkh			v->dwidth = v->width;
93325271Sjkh			v->width = 0;
93425271Sjkh		}
93525271Sjkh		if (v->flag & USER)
93625271Sjkh			needuser = 1;
93725271Sjkh		if (v->flag & COMM)
93825271Sjkh			needcomm = 1;
93925271Sjkh	}
94025271Sjkh}
94125271Sjkh
94225271Sjkhstatic void
94390110Simpdynsizevars(KINFO *ki)
94425271Sjkh{
94525271Sjkh	struct varent *vent;
94625271Sjkh	VAR *v;
9471556Srgrimes	int i;
9481556Srgrimes
9491556Srgrimes	for (vent = vhead; vent; vent = vent->next) {
9501556Srgrimes		v = vent->var;
95125271Sjkh		if (!(v->flag & DSIZ))
95225271Sjkh			continue;
95325271Sjkh		i = (v->sproc)( ki);
95425271Sjkh		if (v->width < i)
95525271Sjkh			v->width = i;
95625271Sjkh		if (v->width > v->dwidth)
95725271Sjkh			v->width = v->dwidth;
95825271Sjkh	}
95925271Sjkh}
96025271Sjkh
96125271Sjkhstatic void
96290110Simpsizevars(void)
96325271Sjkh{
96425271Sjkh	struct varent *vent;
96525271Sjkh	VAR *v;
96625271Sjkh	int i;
96725271Sjkh
96825271Sjkh	for (vent = vhead; vent; vent = vent->next) {
96925271Sjkh		v = vent->var;
970109504Sjmallett		i = strlen(vent->header);
9711556Srgrimes		if (v->width < i)
9721556Srgrimes			v->width = i;
9731556Srgrimes		totwidth += v->width + 1;	/* +1 for space */
9741556Srgrimes	}
9751556Srgrimes	totwidth--;
9761556Srgrimes}
9771556Srgrimes
97890143Smarkmstatic const char *
97990110Simpfmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
980127542Sgad    char *comm, int maxlen)
9811556Srgrimes{
98290143Smarkm	const char *s;
9831556Srgrimes
98490143Smarkm	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
9851556Srgrimes	return (s);
9861556Srgrimes}
9871556Srgrimes
98871578Sjhb#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
98931552Sdyson
9901556Srgrimesstatic void
99190110Simpsaveuser(KINFO *ki)
9921556Srgrimes{
9931556Srgrimes
99471578Sjhb	if (ki->ki_p->ki_sflag & PS_INMEM) {
9951556Srgrimes		/*
9961556Srgrimes		 * The u-area might be swapped out, and we can't get
9971556Srgrimes		 * at it because we have a crashdump and no swap.
9981556Srgrimes		 * If it's here fill in these fields, otherwise, just
9991556Srgrimes		 * leave them 0.
10001556Srgrimes		 */
100169896Smckusick		ki->ki_valid = 1;
10021556Srgrimes	} else
100369896Smckusick		ki->ki_valid = 0;
10041556Srgrimes	/*
10051556Srgrimes	 * save arguments if needed
10061556Srgrimes	 */
100769896Smckusick	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
100890143Smarkm		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
100990143Smarkm		    MAXCOMLEN));
101031552Sdyson	} else if (needcomm) {
101190143Smarkm		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
101253276Speter	} else {
101353276Speter		ki->ki_args = NULL;
101453276Speter	}
101553276Speter	if (needenv && UREADOK(ki)) {
101690143Smarkm		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
101753276Speter	} else if (needenv) {
101853276Speter		ki->ki_env = malloc(3);
101953276Speter		strcpy(ki->ki_env, "()");
102053276Speter	} else {
102153276Speter		ki->ki_env = NULL;
102253276Speter	}
10231556Srgrimes}
10241556Srgrimes
10251556Srgrimesstatic int
102690110Simppscomp(const void *a, const void *b)
10271556Srgrimes{
1028127596Sgad	const KINFO *ka, *kb;
1029127596Sgad	double cpua, cpub;
1030127596Sgad	segsz_t sizea, sizeb;
10311556Srgrimes
1032127596Sgad	ka = a;
1033127596Sgad	kb = b;
1034127596Sgad	/* SORTCPU and SORTMEM are sorted in descending order. */
1035127596Sgad	if (sortby == SORTCPU) {
1036127596Sgad		cpua = getpcpu(ka);
1037127596Sgad		cpub = getpcpu(kb);
1038127596Sgad		if (cpua < cpub)
1039127596Sgad			return (1);
1040127596Sgad		if (cpua > cpub)
1041127596Sgad			return (-1);
1042127596Sgad	}
1043127596Sgad	if (sortby == SORTMEM) {
1044127596Sgad		sizea = ka->ki_p->ki_tsize + ka->ki_p->ki_dsize +
1045127596Sgad		    ka->ki_p->ki_ssize;
1046127596Sgad		sizeb = kb->ki_p->ki_tsize + kb->ki_p->ki_dsize +
1047127596Sgad		    kb->ki_p->ki_ssize;
1048127596Sgad		if (sizea < sizeb)
1049127596Sgad			return (1);
1050127596Sgad		if (sizea > sizeb)
1051127596Sgad			return (-1);
1052127596Sgad	}
1053127596Sgad	/*
1054127596Sgad	 * TTY's are sorted in ascending order, except that all NODEV
1055127596Sgad	 * processes come before all processes with a device.
1056127596Sgad	 */
1057127596Sgad	if (ka->ki_p->ki_tdev == NODEV && kb->ki_p->ki_tdev != NODEV)
1058127596Sgad		return (-1);
1059127596Sgad	if (ka->ki_p->ki_tdev != NODEV && kb->ki_p->ki_tdev == NODEV)
1060127596Sgad		return (1);
1061127596Sgad	if (ka->ki_p->ki_tdev < kb->ki_p->ki_tdev)
1062127596Sgad		return (-1);
1063127596Sgad	if (ka->ki_p->ki_tdev > kb->ki_p->ki_tdev)
1064127596Sgad		return (1);
1065127596Sgad	/* PID's are sorted in ascending order. */
1066127596Sgad	if (ka->ki_p->ki_pid < kb->ki_p->ki_pid)
1067127596Sgad		return (-1);
1068127596Sgad	if (ka->ki_p->ki_pid > kb->ki_p->ki_pid)
1069127596Sgad		return (1);
1070127596Sgad	return (0);
10711556Srgrimes}
10721556Srgrimes
10731556Srgrimes/*
10741556Srgrimes * ICK (all for getopt), would rather hide the ugliness
10751556Srgrimes * here than taint the main code.
10761556Srgrimes *
10771556Srgrimes *  ps foo -> ps -foo
10781556Srgrimes *  ps 34 -> ps -p34
10791556Srgrimes *
10801556Srgrimes * The old convention that 't' with no trailing tty arg means the users
10811556Srgrimes * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
10821556Srgrimes * feature is available with the option 'T', which takes no argument.
10831556Srgrimes */
10841556Srgrimesstatic char *
1085129915Sgadkludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
10861556Srgrimes{
10871556Srgrimes	size_t len;
1088129914Sgad	char *argp, *cp, *newopts, *ns, *optp, *pidp;
10891556Srgrimes
1090102886Sjmallett	/*
1091129914Sgad	 * See if the original value includes any option which takes an
1092129914Sgad	 * argument (and will thus use up the remainder of the string).
1093102886Sjmallett	 */
1094129914Sgad	argp = NULL;
1095129914Sgad	if (optlist != NULL) {
1096129914Sgad		for (cp = origval; *cp != '\0'; cp++) {
1097129914Sgad			optp = strchr(optlist, *cp);
1098129914Sgad			if ((optp != NULL) && *(optp + 1) == ':') {
1099129914Sgad				argp = cp;
1100129914Sgad				break;
1101129914Sgad			}
1102129914Sgad		}
1103129914Sgad	}
1104129914Sgad	if (argp != NULL && *origval == '-')
1105129914Sgad		return (origval);
1106102886Sjmallett
11071556Srgrimes	/*
11081556Srgrimes	 * if last letter is a 't' flag with no argument (in the context
11091556Srgrimes	 * of the oldps options -- option string NOT starting with a '-' --
11101556Srgrimes	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
111181743Sbrian	 *
1112129634Sgad	 * However, if a flag accepting a string argument is found earlier
1113129634Sgad	 * in the option string (including a possible `t' flag), then the
1114129634Sgad	 * remainder of the string must be the argument to that flag; so
1115129914Sgad	 * do not modify that argument.  Note that a trailing `t' would
1116129914Sgad	 * cause argp to be set, if argp was not already set by some
1117129914Sgad	 * earlier option.
11181556Srgrimes	 */
1119129914Sgad	len = strlen(origval);
1120129914Sgad	cp = origval + len - 1;
1121129914Sgad	pidp = NULL;
1122129915Sgad	if (*cp == 't' && *origval != '-' && cp == argp) {
1123129915Sgad		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1124129915Sgad			*cp = 'T';
1125129915Sgad	} else if (argp == NULL) {
11261556Srgrimes		/*
1127129914Sgad		 * The original value did not include any option which takes
1128129914Sgad		 * an argument (and that would include `p' and `t'), so check
1129129914Sgad		 * the value for trailing number, or comma-separated list of
1130129914Sgad		 * numbers, which we will treat as a pid request.
11311556Srgrimes		 */
1132129914Sgad		if (isdigitch(*cp)) {
1133129914Sgad			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1134129914Sgad				--cp;
1135129914Sgad			pidp = cp + 1;
1136129914Sgad		}
11371556Srgrimes	}
1138129914Sgad
11391556Srgrimes	/*
1140129914Sgad	 * If nothing needs to be added to the string, then return
1141129914Sgad	 * the "original" (although possibly modified) value.
11421556Srgrimes	 */
1143129914Sgad	if (*origval == '-' && pidp == NULL)
1144129914Sgad		return (origval);
1145129914Sgad
1146129914Sgad	/*
1147129914Sgad	 * Create a copy of the string to add '-' and/or 'p' to the
1148129914Sgad	 * original value.
1149129914Sgad	 */
1150129914Sgad	if ((newopts = ns = malloc(len + 3)) == NULL)
1151129914Sgad		errx(1, "malloc failed");
1152129914Sgad
1153129914Sgad	if (*origval != '-')
1154129914Sgad		*ns++ = '-';	/* add option flag */
1155129914Sgad
1156129914Sgad	if (pidp == NULL)
1157129914Sgad		strcpy(ns, origval);
1158129914Sgad	else {
1159129914Sgad		/*
1160129914Sgad		 * Copy everything before the pid string, add the `p',
1161129914Sgad		 * and then copy the pid string.
1162129914Sgad		 */
1163129914Sgad		len = pidp - origval;
1164129914Sgad		memcpy(ns, origval, len);
1165129914Sgad		ns += len;
11661556Srgrimes		*ns++ = 'p';
1167129914Sgad		strcpy(ns, pidp);
1168129914Sgad	}
11691556Srgrimes
11701556Srgrimes	return (newopts);
11711556Srgrimes}
11721556Srgrimes
11731556Srgrimesstatic void
117490110Simpusage(void)
11751556Srgrimes{
1176127507Sgad#define	SINGLE_OPTS	"[-aC" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
11771556Srgrimes
1178127499Sgad	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1179127507Sgad	    "usage: ps " SINGLE_OPTS " [-G gid[,gid]] [-O|o fmt]",
1180127499Sgad	    "          [-p pid[,pid]] [-t tty[,tty]] [-U user[,user]]",
1181127499Sgad	    "          [-M core] [-N system]",
118226465Scharnier	    "       ps [-L]");
11831556Srgrimes	exit(1);
11841556Srgrimes}
1185