ps.c revision 129967
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 129967 2004-06-01 22:19:16Z 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 *);
143129952Sgadstatic char	*kludge_oldps_options(const char *, 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)
210129967Sgad		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	 */
430129967Sgad	if (dropgid)
4311556Srgrimes		setgid(getgid());
4321556Srgrimes
43389909Sru	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
4341556Srgrimes	if (kd == 0)
4351556Srgrimes		errx(1, "%s", errbuf);
4361556Srgrimes
43790143Smarkm	if (!_fmt)
438109502Sjmallett		parsefmt(dfmt, 0);
4391556Srgrimes
440127499Sgad	if (nselectors == 0) {
441127823Sgad		uidlist.l.ptr = malloc(sizeof(uid_t));
442127823Sgad		if (uidlist.l.ptr == NULL)
44397877Sjmallett			errx(1, "malloc failed");
444127499Sgad		nselectors = 1;
445127499Sgad		uidlist.count = uidlist.maxcount = 1;
446127823Sgad		*uidlist.l.uids = getuid();
44766377Sbrian	}
4481556Srgrimes
4491556Srgrimes	/*
4501556Srgrimes	 * scan requested variables, noting what structures are needed,
45153170Skris	 * and adjusting header widths as appropriate.
4521556Srgrimes	 */
4531556Srgrimes	scanvars();
454127499Sgad
4551556Srgrimes	/*
456127499Sgad	 * Get process list.  If the user requested just one selector-
457127499Sgad	 * option, then kvm_getprocs can be asked to return just those
458127499Sgad	 * processes.  Otherwise, have it return all processes, and
459127499Sgad	 * then this routine will search that full list and select the
460127499Sgad	 * processes which match any of the user's selector-options.
4611556Srgrimes	 */
462127499Sgad	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
463127499Sgad	flag = 0;
464127499Sgad	if (nselectors == 1) {
465129600Sgad		if (gidlist.count == 1) {
466129600Sgad			what = KERN_PROC_RGID | showthreads;
467129600Sgad			flag = *gidlist.l.gids;
468129600Sgad			nselectors = 0;
469129600Sgad		} else if (pgrplist.count == 1) {
470127499Sgad			what = KERN_PROC_PGRP | showthreads;
471127823Sgad			flag = *pgrplist.l.pids;
472127499Sgad			nselectors = 0;
473127499Sgad		} else if (pidlist.count == 1) {
474127499Sgad			what = KERN_PROC_PID | showthreads;
475127823Sgad			flag = *pidlist.l.pids;
476127499Sgad			nselectors = 0;
477127499Sgad		} else if (ruidlist.count == 1) {
478127499Sgad			what = KERN_PROC_RUID | showthreads;
479127823Sgad			flag = *ruidlist.l.uids;
480127499Sgad			nselectors = 0;
481127499Sgad		} else if (sesslist.count == 1) {
482127499Sgad			what = KERN_PROC_SESSION | showthreads;
483127823Sgad			flag = *sesslist.l.pids;
484127499Sgad			nselectors = 0;
485127499Sgad		} else if (ttylist.count == 1) {
486127499Sgad			what = KERN_PROC_TTY | showthreads;
487127823Sgad			flag = *ttylist.l.ttys;
488127499Sgad			nselectors = 0;
489127499Sgad		} else if (uidlist.count == 1) {
490127499Sgad			what = KERN_PROC_UID | showthreads;
491127823Sgad			flag = *uidlist.l.uids;
492127499Sgad			nselectors = 0;
493127499Sgad		} else if (all) {
494127499Sgad			/* No need for this routine to select processes. */
495127499Sgad			nselectors = 0;
496127499Sgad		}
4971556Srgrimes	}
498126127Sdeischen
4991556Srgrimes	/*
5001556Srgrimes	 * select procs
5011556Srgrimes	 */
502127499Sgad	nentries = -1;
503127149Sgad	kp = kvm_getprocs(kd, what, flag, &nentries);
504127544Sgad	if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
5051556Srgrimes		errx(1, "%s", kvm_geterr(kd));
506127499Sgad	nkept = 0;
507127149Sgad	if (nentries > 0) {
508127149Sgad		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
509127149Sgad			errx(1, "malloc failed");
510127149Sgad		for (i = nentries; --i >= 0; ++kp) {
511127499Sgad			/*
512127499Sgad			 * If the user specified multiple selection-criteria,
513127499Sgad			 * then keep any process matched by the inclusive OR
514127499Sgad			 * of all the selection-criteria given.
515127499Sgad			 */
516127499Sgad			if (pidlist.count > 0) {
517127499Sgad				for (elem = 0; elem < pidlist.count; elem++)
518127823Sgad					if (kp->ki_pid == pidlist.l.pids[elem])
519127499Sgad						goto keepit;
520127499Sgad			}
521127499Sgad			/*
522127499Sgad			 * Note that we had to process pidlist before
523127499Sgad			 * filtering out processes which do not have
524127499Sgad			 * a controlling terminal.
525127499Sgad			 */
526127499Sgad			if (xkeep == 0) {
527127499Sgad				if ((kp->ki_tdev == NODEV ||
528127499Sgad				    (kp->ki_flag & P_CONTROLT) == 0))
529127499Sgad					continue;
530127499Sgad			}
531127499Sgad			if (nselectors == 0)
532127499Sgad				goto keepit;
533127499Sgad			if (gidlist.count > 0) {
534127499Sgad				for (elem = 0; elem < gidlist.count; elem++)
535127823Sgad					if (kp->ki_rgid == gidlist.l.gids[elem])
536127499Sgad						goto keepit;
537127499Sgad			}
538127499Sgad			if (pgrplist.count > 0) {
539127499Sgad				for (elem = 0; elem < pgrplist.count; elem++)
540127823Sgad					if (kp->ki_pgid ==
541127823Sgad					    pgrplist.l.pids[elem])
542127499Sgad						goto keepit;
543127499Sgad			}
544127499Sgad			if (ruidlist.count > 0) {
545127499Sgad				for (elem = 0; elem < ruidlist.count; elem++)
546127823Sgad					if (kp->ki_ruid ==
547127823Sgad					    ruidlist.l.uids[elem])
548127499Sgad						goto keepit;
549127499Sgad			}
550127499Sgad			if (sesslist.count > 0) {
551127499Sgad				for (elem = 0; elem < sesslist.count; elem++)
552127823Sgad					if (kp->ki_sid == sesslist.l.pids[elem])
553127499Sgad						goto keepit;
554127499Sgad			}
555127499Sgad			if (ttylist.count > 0) {
556127499Sgad				for (elem = 0; elem < ttylist.count; elem++)
557127823Sgad					if (kp->ki_tdev == ttylist.l.ttys[elem])
558127499Sgad						goto keepit;
559127499Sgad			}
560127499Sgad			if (uidlist.count > 0) {
561127499Sgad				for (elem = 0; elem < uidlist.count; elem++)
562127823Sgad					if (kp->ki_uid == uidlist.l.uids[elem])
563127499Sgad						goto keepit;
564127499Sgad			}
565127499Sgad			/*
566127499Sgad			 * This process did not match any of the user's
567127499Sgad			 * selector-options, so skip the process.
568127499Sgad			 */
569127499Sgad			continue;
570127499Sgad
571127499Sgad		keepit:
572127499Sgad			kinfo[nkept].ki_p = kp;
573127149Sgad			if (needuser)
574127499Sgad				saveuser(&kinfo[nkept]);
575127499Sgad			dynsizevars(&kinfo[nkept]);
576127499Sgad			nkept++;
577127149Sgad		}
5781556Srgrimes	}
57925271Sjkh
58025271Sjkh	sizevars();
58125271Sjkh
5821556Srgrimes	/*
5831556Srgrimes	 * print header
5841556Srgrimes	 */
5851556Srgrimes	printheader();
586127499Sgad	if (nkept == 0)
58762803Swill		exit(1);
588127499Sgad
5891556Srgrimes	/*
5901556Srgrimes	 * sort proc list
5911556Srgrimes	 */
592127499Sgad	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
5931556Srgrimes	/*
594127499Sgad	 * For each process, call each variable output function.
5951556Srgrimes	 */
596127499Sgad	for (i = lineno = 0; i < nkept; i++) {
5971556Srgrimes		for (vent = vhead; vent; vent = vent->next) {
5981556Srgrimes			(vent->var->oproc)(&kinfo[i], vent);
5991556Srgrimes			if (vent->next != NULL)
6001556Srgrimes				(void)putchar(' ');
6011556Srgrimes		}
6021556Srgrimes		(void)putchar('\n');
6031556Srgrimes		if (prtheader && lineno++ == prtheader - 4) {
6041556Srgrimes			(void)putchar('\n');
6051556Srgrimes			printheader();
6061556Srgrimes			lineno = 0;
6071556Srgrimes		}
6081556Srgrimes	}
609127499Sgad	free_list(&gidlist);
610127499Sgad	free_list(&pidlist);
611127499Sgad	free_list(&pgrplist);
612127499Sgad	free_list(&ruidlist);
613127499Sgad	free_list(&sesslist);
614127499Sgad	free_list(&ttylist);
615127499Sgad	free_list(&uidlist);
61666377Sbrian
6171556Srgrimes	exit(eval);
6181556Srgrimes}
6191556Srgrimes
620127499Sgadstatic int
621127499Sgadaddelem_gid(struct listinfo *inf, const char *elem)
622127499Sgad{
623127499Sgad	struct group *grp;
624127499Sgad	const char *nameorID;
625127499Sgad	char *endp;
626127602Sgad	u_long bigtemp;
627127499Sgad
628127499Sgad	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
629127499Sgad		if (*elem == '\0')
630127499Sgad			warnx("Invalid (zero-length) %s name", inf->lname);
631127499Sgad		else
632127499Sgad			warnx("%s name too long: %s", inf->lname, elem);
633127499Sgad		optfatal = 1;
634127542Sgad		return (0);		/* Do not add this value. */
635127499Sgad	}
636127499Sgad
637127499Sgad	/*
638127499Sgad	 * SUSv3 states that `ps -G grouplist' should match "real-group
639127499Sgad	 * ID numbers", and does not mention group-names.  I do want to
640127499Sgad	 * also support group-names, so this tries for a group-id first,
641127499Sgad	 * and only tries for a name if that doesn't work.  This is the
642127499Sgad	 * opposite order of what is done in addelem_uid(), but in
643127499Sgad	 * practice the order would only matter for group-names which
644127499Sgad	 * are all-numeric.
645127499Sgad	 */
646127499Sgad	grp = NULL;
647127499Sgad	nameorID = "named";
648127499Sgad	errno = 0;
649127602Sgad	bigtemp = strtoul(elem, &endp, 10);
650127602Sgad	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
651127499Sgad		nameorID = "name or ID matches";
652127602Sgad		grp = getgrgid((gid_t)bigtemp);
653127499Sgad	}
654127499Sgad	if (grp == NULL)
655127499Sgad		grp = getgrnam(elem);
656127499Sgad	if (grp == NULL) {
657127499Sgad		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
658127499Sgad		optfatal = 1;
659129967Sgad		return (0);
660127499Sgad	}
661127499Sgad	if (inf->count >= inf->maxcount)
662127499Sgad		expand_list(inf);
663127823Sgad	inf->l.gids[(inf->count)++] = grp->gr_gid;
664127499Sgad	return (1);
665127499Sgad}
666127499Sgad
667127597Sgad#define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h. */
668127499Sgadstatic int
669127499Sgadaddelem_pid(struct listinfo *inf, const char *elem)
670127149Sgad{
671127539Sgad	char *endp;
672127149Sgad	long tempid;
673127149Sgad
674129917Sgad	if (*elem == '\0') {
675129917Sgad		warnx("Invalid (zero-length) process id");
676129917Sgad		optfatal = 1;
677129917Sgad		return (0);		/* Do not add this value. */
678127149Sgad	}
679127149Sgad
680129952Sgad	errno = 0;
681129952Sgad	tempid = strtol(elem, &endp, 10);
682129952Sgad	if (*endp != '\0' || tempid < 0 || elem == endp) {
683129952Sgad		warnx("Invalid %s: %s", inf->lname, elem);
684129952Sgad		errno = ERANGE;
685129952Sgad	} else if (errno != 0 || tempid > BSD_PID_MAX) {
686129952Sgad		warnx("%s too large: %s", inf->lname, elem);
687129952Sgad		errno = ERANGE;
688129952Sgad	}
689129952Sgad	if (errno == ERANGE) {
690129952Sgad		optfatal = 1;
691129967Sgad		return (0);
692129952Sgad	}
693127499Sgad	if (inf->count >= inf->maxcount)
694127499Sgad		expand_list(inf);
695127823Sgad	inf->l.pids[(inf->count)++] = tempid;
696127499Sgad	return (1);
697127499Sgad}
698127499Sgad#undef	BSD_PID_MAX
699127149Sgad
700127499Sgadstatic int
701127499Sgadaddelem_tty(struct listinfo *inf, const char *elem)
702127499Sgad{
703127539Sgad	const char *ttypath;
704127539Sgad	struct stat sb;
705127499Sgad	char pathbuf[PATH_MAX];
706127499Sgad
707127499Sgad	if (strcmp(elem, "co") == 0)
708127499Sgad		ttypath = strdup(_PATH_CONSOLE);
709127499Sgad	else if (*elem == '/')
710127499Sgad		ttypath = elem;
711127499Sgad	else {
712127499Sgad		strlcpy(pathbuf, _PATH_TTY, sizeof(pathbuf));
713127499Sgad		strlcat(pathbuf, elem, sizeof(pathbuf));
714127499Sgad		ttypath = pathbuf;
715127499Sgad	}
716127499Sgad
717127499Sgad	if (stat(ttypath, &sb) == -1) {
718127499Sgad		warn("%s", ttypath);
719127499Sgad		optfatal = 1;
720129967Sgad		return (0);
721127499Sgad	}
722127499Sgad	if (!S_ISCHR(sb.st_mode)) {
723127499Sgad		warn("%s: Not a terminal", ttypath);
724127499Sgad		optfatal = 1;
725129967Sgad		return (0);
726127499Sgad	}
727127499Sgad	if (inf->count >= inf->maxcount)
728127499Sgad		expand_list(inf);
729127823Sgad	inf->l.ttys[(inf->count)++] = sb.st_rdev;
730127499Sgad	return (1);
731127149Sgad}
732127149Sgad
733127499Sgadstatic int
734127499Sgadaddelem_uid(struct listinfo *inf, const char *elem)
73566377Sbrian{
73666377Sbrian	struct passwd *pwd;
737127539Sgad	char *endp;
738127602Sgad	u_long bigtemp;
73966377Sbrian
740127499Sgad	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
741127499Sgad		if (*elem == '\0')
742127499Sgad			warnx("Invalid (zero-length) %s name", inf->lname);
743127499Sgad		else
744127499Sgad			warnx("%s name too long: %s", inf->lname, elem);
745127499Sgad		optfatal = 1;
746127542Sgad		return (0);		/* Do not add this value. */
747127499Sgad	}
74866377Sbrian
749127499Sgad	pwd = getpwnam(elem);
750127499Sgad	if (pwd == NULL) {
751127499Sgad		errno = 0;
752127602Sgad		bigtemp = strtoul(elem, &endp, 10);
753127602Sgad		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
754127499Sgad			warnx("No %s named '%s'", inf->lname, elem);
755127499Sgad		else {
756127499Sgad			/* The string is all digits, so it might be a userID. */
757127602Sgad			pwd = getpwuid((uid_t)bigtemp);
758127499Sgad			if (pwd == NULL)
759127499Sgad				warnx("No %s name or ID matches '%s'",
760127499Sgad				    inf->lname, elem);
76166377Sbrian		}
762127499Sgad	}
763127499Sgad	if (pwd == NULL) {
764127509Sgad		/*
765127509Sgad		 * These used to be treated as minor warnings (and the
766127509Sgad		 * option was simply ignored), but now they are fatal
767127509Sgad		 * errors (and the command will be aborted).
768127509Sgad		 */
769127509Sgad		optfatal = 1;
770129967Sgad		return (0);
771127499Sgad	}
772127499Sgad	if (inf->count >= inf->maxcount)
773127499Sgad		expand_list(inf);
774127823Sgad	inf->l.uids[(inf->count)++] = pwd->pw_uid;
775127499Sgad	return (1);
776127499Sgad}
777127499Sgad
778127499Sgadstatic void
779127499Sgadadd_list(struct listinfo *inf, const char *argp)
780127499Sgad{
781127499Sgad	const char *savep;
782127499Sgad	char *cp, *endp;
783127499Sgad	int toolong;
784127539Sgad	char elemcopy[PATH_MAX];
785127499Sgad
786129917Sgad	if (*argp == 0)
787129967Sgad		inf->addelem(inf, elemcopy);
788127499Sgad	while (*argp != '\0') {
789127499Sgad		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
790127499Sgad			argp++;
791127499Sgad		savep = argp;
792127499Sgad		toolong = 0;
793127499Sgad		cp = elemcopy;
794127499Sgad		if (strchr(T_SEP, *argp) == NULL) {
795127499Sgad			endp = elemcopy + sizeof(elemcopy) - 1;
796127499Sgad			while (*argp != '\0' && cp <= endp &&
797127499Sgad			    strchr(W_SEP T_SEP, *argp) == NULL)
798127499Sgad				*cp++ = *argp++;
799127499Sgad			if (cp > endp)
800127499Sgad				toolong = 1;
80166377Sbrian		}
802127499Sgad		if (!toolong) {
803127499Sgad			*cp = '\0';
804127542Sgad			/*
805129953Sgad			 * Add this single element to the given list.
806127542Sgad			 */
807127499Sgad			inf->addelem(inf, elemcopy);
808127499Sgad		} else {
809127499Sgad			/*
810127499Sgad			 * The string is too long to copy.  Find the end
811127499Sgad			 * of the string to print out the warning message.
812127499Sgad			 */
813127499Sgad			while (*argp != '\0' && strchr(W_SEP T_SEP,
814127499Sgad			    *argp) == NULL)
815127499Sgad				argp++;
816127499Sgad			warnx("Value too long: %.*s", (int)(argp - savep),
817127499Sgad			    savep);
818127499Sgad			optfatal = 1;
81966377Sbrian		}
820127499Sgad		/*
821127499Sgad		 * Skip over any number of trailing whitespace characters,
822127499Sgad		 * but only one (at most) trailing element-terminating
823127499Sgad		 * character.
824127499Sgad		 */
825127499Sgad		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
826127499Sgad			argp++;
827127499Sgad		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
828127499Sgad			argp++;
829127499Sgad			/* Catch case where string ended with a comma. */
830127499Sgad			if (*argp == '\0')
831127499Sgad				inf->addelem(inf, argp);
832127499Sgad		}
83366377Sbrian	}
834127499Sgad}
83566377Sbrian
836127499Sgadstatic void *
837127499Sgadexpand_list(struct listinfo *inf)
838127499Sgad{
839127539Sgad	void *newlist;
840127499Sgad	int newmax;
84166377Sbrian
842127499Sgad	newmax = (inf->maxcount + 1) << 1;
843127823Sgad	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
844127499Sgad	if (newlist == NULL) {
845127823Sgad		free(inf->l.ptr);
846129967Sgad		errx(1, "realloc to %d %ss failed", newmax, inf->lname);
847127499Sgad	}
848127499Sgad	inf->maxcount = newmax;
849127823Sgad	inf->l.ptr = newlist;
850127499Sgad
851127499Sgad	return (newlist);
85266377Sbrian}
85366377Sbrian
854127499Sgadstatic void
855127499Sgadfree_list(struct listinfo *inf)
856127499Sgad{
857127499Sgad
858127499Sgad	inf->count = inf->elemsize = inf->maxcount = 0;
859127823Sgad	if (inf->l.ptr != NULL)
860127823Sgad		free(inf->l.ptr);
861127499Sgad	inf->addelem = NULL;
862127499Sgad	inf->lname = NULL;
863127823Sgad	inf->l.ptr = NULL;
864127499Sgad}
865127499Sgad
866127499Sgadstatic void
867127499Sgadinit_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
868127499Sgad    const char *lname)
869127499Sgad{
870127499Sgad
871127499Sgad	inf->count = inf->maxcount = 0;
872127499Sgad	inf->elemsize = elemsize;
873127499Sgad	inf->addelem = artn;
874127499Sgad	inf->lname = lname;
875127823Sgad	inf->l.ptr = NULL;
876127499Sgad}
877127499Sgad
878109502SjmallettVARENT *
879109502Sjmallettfind_varentry(VAR *v)
880109502Sjmallett{
881109502Sjmallett	struct varent *vent;
882109502Sjmallett
883109502Sjmallett	for (vent = vhead; vent; vent = vent->next) {
884109502Sjmallett		if (strcmp(vent->var->name, v->name) == 0)
885109502Sjmallett			return vent;
886109502Sjmallett	}
887109502Sjmallett	return NULL;
888109502Sjmallett}
889109502Sjmallett
8901556Srgrimesstatic void
89190110Simpscanvars(void)
8921556Srgrimes{
8931556Srgrimes	struct varent *vent;
8941556Srgrimes	VAR *v;
89525271Sjkh
89625271Sjkh	for (vent = vhead; vent; vent = vent->next) {
89725271Sjkh		v = vent->var;
89825271Sjkh		if (v->flag & DSIZ) {
89925271Sjkh			v->dwidth = v->width;
90025271Sjkh			v->width = 0;
90125271Sjkh		}
90225271Sjkh		if (v->flag & USER)
90325271Sjkh			needuser = 1;
90425271Sjkh		if (v->flag & COMM)
90525271Sjkh			needcomm = 1;
90625271Sjkh	}
90725271Sjkh}
90825271Sjkh
90925271Sjkhstatic void
91090110Simpdynsizevars(KINFO *ki)
91125271Sjkh{
91225271Sjkh	struct varent *vent;
91325271Sjkh	VAR *v;
9141556Srgrimes	int i;
9151556Srgrimes
9161556Srgrimes	for (vent = vhead; vent; vent = vent->next) {
9171556Srgrimes		v = vent->var;
91825271Sjkh		if (!(v->flag & DSIZ))
91925271Sjkh			continue;
92025271Sjkh		i = (v->sproc)( ki);
92125271Sjkh		if (v->width < i)
92225271Sjkh			v->width = i;
92325271Sjkh		if (v->width > v->dwidth)
92425271Sjkh			v->width = v->dwidth;
92525271Sjkh	}
92625271Sjkh}
92725271Sjkh
92825271Sjkhstatic void
92990110Simpsizevars(void)
93025271Sjkh{
93125271Sjkh	struct varent *vent;
93225271Sjkh	VAR *v;
93325271Sjkh	int i;
93425271Sjkh
93525271Sjkh	for (vent = vhead; vent; vent = vent->next) {
93625271Sjkh		v = vent->var;
937109504Sjmallett		i = strlen(vent->header);
9381556Srgrimes		if (v->width < i)
9391556Srgrimes			v->width = i;
9401556Srgrimes		totwidth += v->width + 1;	/* +1 for space */
9411556Srgrimes	}
9421556Srgrimes	totwidth--;
9431556Srgrimes}
9441556Srgrimes
94590143Smarkmstatic const char *
94690110Simpfmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
947127542Sgad    char *comm, int maxlen)
9481556Srgrimes{
94990143Smarkm	const char *s;
9501556Srgrimes
95190143Smarkm	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
9521556Srgrimes	return (s);
9531556Srgrimes}
9541556Srgrimes
95571578Sjhb#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
95631552Sdyson
9571556Srgrimesstatic void
95890110Simpsaveuser(KINFO *ki)
9591556Srgrimes{
9601556Srgrimes
96171578Sjhb	if (ki->ki_p->ki_sflag & PS_INMEM) {
9621556Srgrimes		/*
9631556Srgrimes		 * The u-area might be swapped out, and we can't get
9641556Srgrimes		 * at it because we have a crashdump and no swap.
9651556Srgrimes		 * If it's here fill in these fields, otherwise, just
9661556Srgrimes		 * leave them 0.
9671556Srgrimes		 */
96869896Smckusick		ki->ki_valid = 1;
9691556Srgrimes	} else
97069896Smckusick		ki->ki_valid = 0;
9711556Srgrimes	/*
9721556Srgrimes	 * save arguments if needed
9731556Srgrimes	 */
97469896Smckusick	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
97590143Smarkm		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
97690143Smarkm		    MAXCOMLEN));
97731552Sdyson	} else if (needcomm) {
97890143Smarkm		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
97953276Speter	} else {
98053276Speter		ki->ki_args = NULL;
98153276Speter	}
98253276Speter	if (needenv && UREADOK(ki)) {
98390143Smarkm		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
98453276Speter	} else if (needenv) {
98553276Speter		ki->ki_env = malloc(3);
98653276Speter		strcpy(ki->ki_env, "()");
98753276Speter	} else {
98853276Speter		ki->ki_env = NULL;
98953276Speter	}
9901556Srgrimes}
9911556Srgrimes
9921556Srgrimesstatic int
99390110Simppscomp(const void *a, const void *b)
9941556Srgrimes{
995127596Sgad	const KINFO *ka, *kb;
996127596Sgad	double cpua, cpub;
997127596Sgad	segsz_t sizea, sizeb;
9981556Srgrimes
999127596Sgad	ka = a;
1000127596Sgad	kb = b;
1001127596Sgad	/* SORTCPU and SORTMEM are sorted in descending order. */
1002127596Sgad	if (sortby == SORTCPU) {
1003127596Sgad		cpua = getpcpu(ka);
1004127596Sgad		cpub = getpcpu(kb);
1005127596Sgad		if (cpua < cpub)
1006127596Sgad			return (1);
1007127596Sgad		if (cpua > cpub)
1008127596Sgad			return (-1);
1009127596Sgad	}
1010127596Sgad	if (sortby == SORTMEM) {
1011127596Sgad		sizea = ka->ki_p->ki_tsize + ka->ki_p->ki_dsize +
1012127596Sgad		    ka->ki_p->ki_ssize;
1013127596Sgad		sizeb = kb->ki_p->ki_tsize + kb->ki_p->ki_dsize +
1014127596Sgad		    kb->ki_p->ki_ssize;
1015127596Sgad		if (sizea < sizeb)
1016127596Sgad			return (1);
1017127596Sgad		if (sizea > sizeb)
1018127596Sgad			return (-1);
1019127596Sgad	}
1020127596Sgad	/*
1021127596Sgad	 * TTY's are sorted in ascending order, except that all NODEV
1022127596Sgad	 * processes come before all processes with a device.
1023127596Sgad	 */
1024127596Sgad	if (ka->ki_p->ki_tdev == NODEV && kb->ki_p->ki_tdev != NODEV)
1025127596Sgad		return (-1);
1026127596Sgad	if (ka->ki_p->ki_tdev != NODEV && kb->ki_p->ki_tdev == NODEV)
1027127596Sgad		return (1);
1028127596Sgad	if (ka->ki_p->ki_tdev < kb->ki_p->ki_tdev)
1029127596Sgad		return (-1);
1030127596Sgad	if (ka->ki_p->ki_tdev > kb->ki_p->ki_tdev)
1031127596Sgad		return (1);
1032127596Sgad	/* PID's are sorted in ascending order. */
1033127596Sgad	if (ka->ki_p->ki_pid < kb->ki_p->ki_pid)
1034127596Sgad		return (-1);
1035127596Sgad	if (ka->ki_p->ki_pid > kb->ki_p->ki_pid)
1036127596Sgad		return (1);
1037127596Sgad	return (0);
10381556Srgrimes}
10391556Srgrimes
10401556Srgrimes/*
10411556Srgrimes * ICK (all for getopt), would rather hide the ugliness
10421556Srgrimes * here than taint the main code.
10431556Srgrimes *
10441556Srgrimes *  ps foo -> ps -foo
10451556Srgrimes *  ps 34 -> ps -p34
10461556Srgrimes *
10471556Srgrimes * The old convention that 't' with no trailing tty arg means the users
10481556Srgrimes * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
10491556Srgrimes * feature is available with the option 'T', which takes no argument.
10501556Srgrimes */
10511556Srgrimesstatic char *
1052129915Sgadkludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
10531556Srgrimes{
10541556Srgrimes	size_t len;
1055129914Sgad	char *argp, *cp, *newopts, *ns, *optp, *pidp;
10561556Srgrimes
1057102886Sjmallett	/*
1058129914Sgad	 * See if the original value includes any option which takes an
1059129914Sgad	 * argument (and will thus use up the remainder of the string).
1060102886Sjmallett	 */
1061129914Sgad	argp = NULL;
1062129914Sgad	if (optlist != NULL) {
1063129914Sgad		for (cp = origval; *cp != '\0'; cp++) {
1064129914Sgad			optp = strchr(optlist, *cp);
1065129914Sgad			if ((optp != NULL) && *(optp + 1) == ':') {
1066129914Sgad				argp = cp;
1067129914Sgad				break;
1068129914Sgad			}
1069129914Sgad		}
1070129914Sgad	}
1071129914Sgad	if (argp != NULL && *origval == '-')
1072129914Sgad		return (origval);
1073102886Sjmallett
10741556Srgrimes	/*
10751556Srgrimes	 * if last letter is a 't' flag with no argument (in the context
10761556Srgrimes	 * of the oldps options -- option string NOT starting with a '-' --
10771556Srgrimes	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
107881743Sbrian	 *
1079129634Sgad	 * However, if a flag accepting a string argument is found earlier
1080129634Sgad	 * in the option string (including a possible `t' flag), then the
1081129634Sgad	 * remainder of the string must be the argument to that flag; so
1082129914Sgad	 * do not modify that argument.  Note that a trailing `t' would
1083129914Sgad	 * cause argp to be set, if argp was not already set by some
1084129914Sgad	 * earlier option.
10851556Srgrimes	 */
1086129914Sgad	len = strlen(origval);
1087129914Sgad	cp = origval + len - 1;
1088129914Sgad	pidp = NULL;
1089129915Sgad	if (*cp == 't' && *origval != '-' && cp == argp) {
1090129915Sgad		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1091129915Sgad			*cp = 'T';
1092129915Sgad	} else if (argp == NULL) {
10931556Srgrimes		/*
1094129914Sgad		 * The original value did not include any option which takes
1095129914Sgad		 * an argument (and that would include `p' and `t'), so check
1096129914Sgad		 * the value for trailing number, or comma-separated list of
1097129914Sgad		 * numbers, which we will treat as a pid request.
10981556Srgrimes		 */
1099129914Sgad		if (isdigitch(*cp)) {
1100129914Sgad			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1101129914Sgad				--cp;
1102129914Sgad			pidp = cp + 1;
1103129914Sgad		}
11041556Srgrimes	}
1105129914Sgad
11061556Srgrimes	/*
1107129914Sgad	 * If nothing needs to be added to the string, then return
1108129914Sgad	 * the "original" (although possibly modified) value.
11091556Srgrimes	 */
1110129914Sgad	if (*origval == '-' && pidp == NULL)
1111129914Sgad		return (origval);
1112129914Sgad
1113129914Sgad	/*
1114129914Sgad	 * Create a copy of the string to add '-' and/or 'p' to the
1115129914Sgad	 * original value.
1116129914Sgad	 */
1117129914Sgad	if ((newopts = ns = malloc(len + 3)) == NULL)
1118129914Sgad		errx(1, "malloc failed");
1119129914Sgad
1120129914Sgad	if (*origval != '-')
1121129914Sgad		*ns++ = '-';	/* add option flag */
1122129914Sgad
1123129914Sgad	if (pidp == NULL)
1124129914Sgad		strcpy(ns, origval);
1125129914Sgad	else {
1126129914Sgad		/*
1127129914Sgad		 * Copy everything before the pid string, add the `p',
1128129914Sgad		 * and then copy the pid string.
1129129914Sgad		 */
1130129914Sgad		len = pidp - origval;
1131129914Sgad		memcpy(ns, origval, len);
1132129914Sgad		ns += len;
11331556Srgrimes		*ns++ = 'p';
1134129914Sgad		strcpy(ns, pidp);
1135129914Sgad	}
11361556Srgrimes
11371556Srgrimes	return (newopts);
11381556Srgrimes}
11391556Srgrimes
11401556Srgrimesstatic void
114190110Simpusage(void)
11421556Srgrimes{
1143127507Sgad#define	SINGLE_OPTS	"[-aC" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
11441556Srgrimes
1145127499Sgad	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1146127507Sgad	    "usage: ps " SINGLE_OPTS " [-G gid[,gid]] [-O|o fmt]",
1147127499Sgad	    "          [-p pid[,pid]] [-t tty[,tty]] [-U user[,user]]",
1148127499Sgad	    "          [-M core] [-N system]",
114926465Scharnier	    "       ps [-L]");
11501556Srgrimes	exit(1);
11511556Srgrimes}
1152