ps.c revision 130999
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 130999 2004-06-23 23:48:09Z 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/*
88129971Sgad * isdigit takes an `int', but expects values in the range of unsigned char.
89129971Sgad * This wrapper ensures that values from a 'char' end up in the correct range.
90129914Sgad */
91129971Sgad#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
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
101130999Sgadstruct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
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;
169130816Sgad	KINFO *next_KINFO;
1701556Srgrimes	struct varent *vent;
1711556Srgrimes	struct winsize ws;
172129914Sgad	const char *nlistf, *memf;
173127539Sgad	char *cols;
174127499Sgad	int all, ch, dropgid, elem, flag, _fmt, i, lineno;
175129914Sgad	int nentries, nkept, nselectors;
176127499Sgad	int prtheader, showthreads, wflag, what, xkeep, xkeep_implied;
17790143Smarkm	char errbuf[_POSIX2_LINE_MAX];
1781556Srgrimes
17911809Sache	(void) setlocale(LC_ALL, "");
180127542Sgad	time(&now);			/* Used by routines in print.c. */
18111809Sache
18297804Stjr	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
18397804Stjr		termwidth = atoi(cols);
18497804Stjr	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1851556Srgrimes	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1861556Srgrimes	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
1871556Srgrimes	     ws.ws_col == 0)
1881556Srgrimes		termwidth = 79;
1891556Srgrimes	else
1901556Srgrimes		termwidth = ws.ws_col - 1;
1911556Srgrimes
19298494Ssobomax	/*
193129914Sgad	 * Hide a number of option-processing kludges in a separate routine,
194129914Sgad	 * to support some historical BSD behaviors, such as `ps axu'.
19598494Ssobomax	 */
196129914Sgad	if (argc > 1)
197129915Sgad		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
1981556Srgrimes
199127542Sgad	all = dropgid = _fmt = nselectors = optfatal = 0;
200127542Sgad	prtheader = showthreads = wflag = xkeep_implied = 0;
201127542Sgad	xkeep = -1;			/* Neither -x nor -X. */
202127499Sgad	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
203127499Sgad	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
204127499Sgad	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
205127499Sgad	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
206127499Sgad	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
207127499Sgad	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
208127499Sgad	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
20989909Sru	memf = nlistf = _PATH_DEVNULL;
21098494Ssobomax	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
211129967Sgad		switch ((char)ch) {
212127499Sgad		case 'A':
213127499Sgad			/*
214127499Sgad			 * Exactly the same as `-ax'.   This has been
215127499Sgad			 * added for compatability with SUSv3, but for
216127499Sgad			 * now it will not be described in the man page.
217127499Sgad			 */
218127499Sgad			nselectors++;
219127499Sgad			all = xkeep = 1;
220127499Sgad			break;
2211556Srgrimes		case 'a':
222127499Sgad			nselectors++;
2231556Srgrimes			all = 1;
2241556Srgrimes			break;
22519068Speter		case 'C':
22619068Speter			rawcpu = 1;
22719068Speter			break;
22819068Speter		case 'c':
22919068Speter			cflag = 1;
23019068Speter			break;
2311556Srgrimes		case 'e':			/* XXX set ufmt */
2321556Srgrimes			needenv = 1;
2331556Srgrimes			break;
234127506Sgad#ifdef LAZY_PS
235127506Sgad		case 'f':
236127506Sgad			if (getuid() == 0 || getgid() == 0)
237127542Sgad				forceuread = 1;
238127506Sgad			break;
239127506Sgad#endif
240127499Sgad		case 'G':
241127499Sgad			add_list(&gidlist, optarg);
242127499Sgad			xkeep_implied = 1;
243127499Sgad			nselectors++;
244127499Sgad			break;
245127542Sgad		case 'g':
246127499Sgad#if 0
247127597Sgad			/*-
248127542Sgad			 * XXX - This SUSv3 behavior is still under debate
249127542Sgad			 *	since it conflicts with the (undocumented)
250127542Sgad			 *	`-g' option.  So we skip it for now.
251127542Sgad			 */
252127499Sgad			add_list(&pgrplist, optarg);
253127499Sgad			xkeep_implied = 1;
254127499Sgad			nselectors++;
255127499Sgad			break;
256127499Sgad#else
257127542Sgad			/* The historical BSD-ish (from SunOS) behavior. */
2581556Srgrimes			break;			/* no-op */
259127499Sgad#endif
260116265Sscottl		case 'H':
261126127Sdeischen			showthreads = KERN_PROC_INC_THREAD;
262116265Sscottl			break;
2631556Srgrimes		case 'h':
2641556Srgrimes			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
2651556Srgrimes			break;
2661556Srgrimes		case 'j':
267109502Sjmallett			parsefmt(jfmt, 0);
26890143Smarkm			_fmt = 1;
2691556Srgrimes			jfmt[0] = '\0';
2701556Srgrimes			break;
2711556Srgrimes		case 'L':
2721556Srgrimes			showkey();
2731556Srgrimes			exit(0);
2741556Srgrimes		case 'l':
275109502Sjmallett			parsefmt(lfmt, 0);
27690143Smarkm			_fmt = 1;
2771556Srgrimes			lfmt[0] = '\0';
2781556Srgrimes			break;
2791556Srgrimes		case 'M':
2801556Srgrimes			memf = optarg;
28137317Sphk			dropgid = 1;
2821556Srgrimes			break;
2831556Srgrimes		case 'm':
2841556Srgrimes			sortby = SORTMEM;
2851556Srgrimes			break;
2861556Srgrimes		case 'N':
2871556Srgrimes			nlistf = optarg;
28837317Sphk			dropgid = 1;
2891556Srgrimes			break;
2901556Srgrimes		case 'O':
291109502Sjmallett			parsefmt(o1, 1);
292109502Sjmallett			parsefmt(optarg, 1);
293109502Sjmallett			parsefmt(o2, 1);
2941556Srgrimes			o1[0] = o2[0] = '\0';
29590143Smarkm			_fmt = 1;
2961556Srgrimes			break;
2971556Srgrimes		case 'o':
298109502Sjmallett			parsefmt(optarg, 1);
29990143Smarkm			_fmt = 1;
3001556Srgrimes			break;
3011556Srgrimes		case 'p':
302127499Sgad			add_list(&pidlist, optarg);
303127499Sgad			/*
304127499Sgad			 * Note: `-p' does not *set* xkeep, but any values
305127499Sgad			 * from pidlist are checked before xkeep is.  That
306127499Sgad			 * way they are always matched, even if the user
307127499Sgad			 * specifies `-X'.
308127499Sgad			 */
309127499Sgad			nselectors++;
3101556Srgrimes			break;
311127499Sgad#if 0
312127499Sgad		case 'R':
313127597Sgad			/*-
314127542Sgad			 * XXX - This un-standard option is still under
315127542Sgad			 *	debate.  This is what SUSv3 defines as
316127542Sgad			 *	the `-U' option, and while it would be
317127542Sgad			 *	nice to have, it could cause even more
318127542Sgad			 *	confusion to implement it as `-R'.
319127542Sgad			 */
320127499Sgad			add_list(&ruidlist, optarg);
321127499Sgad			xkeep_implied = 1;
322127499Sgad			nselectors++;
323127499Sgad			break;
324127499Sgad#endif
3251556Srgrimes		case 'r':
3261556Srgrimes			sortby = SORTCPU;
3271556Srgrimes			break;
3281556Srgrimes		case 'S':
3291556Srgrimes			sumrusage = 1;
3301556Srgrimes			break;
331127499Sgad#if 0
332127499Sgad		case 's':
333127597Sgad			/*-
334127542Sgad			 * XXX - This non-standard option is still under
335127542Sgad			 *	debate.  This *is* supported on Solaris,
336127542Sgad			 *	Linux, and IRIX, but conflicts with `-s'
337127542Sgad			 *	on NetBSD and maybe some older BSD's.
338127542Sgad			 */
339127499Sgad			add_list(&sesslist, optarg);
340127499Sgad			xkeep_implied = 1;
341127499Sgad			nselectors++;
342127499Sgad			break;
343127499Sgad#endif
3441556Srgrimes		case 'T':
3451556Srgrimes			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
3461556Srgrimes				errx(1, "stdin: not a terminal");
3471556Srgrimes			/* FALLTHROUGH */
348127499Sgad		case 't':
349127499Sgad			add_list(&ttylist, optarg);
350127499Sgad			xkeep_implied = 1;
351127499Sgad			nselectors++;
3521556Srgrimes			break;
35313020Speter		case 'U':
354127499Sgad			/* This is what SUSv3 defines as the `-u' option. */
355127499Sgad			add_list(&uidlist, optarg);
356127499Sgad			xkeep_implied = 1;
357127499Sgad			nselectors++;
35813020Speter			break;
3591556Srgrimes		case 'u':
360109502Sjmallett			parsefmt(ufmt, 0);
3611556Srgrimes			sortby = SORTCPU;
36290143Smarkm			_fmt = 1;
3631556Srgrimes			ufmt[0] = '\0';
3641556Srgrimes			break;
3651556Srgrimes		case 'v':
366109502Sjmallett			parsefmt(vfmt, 0);
3671556Srgrimes			sortby = SORTMEM;
36890143Smarkm			_fmt = 1;
3691556Srgrimes			vfmt[0] = '\0';
3701556Srgrimes			break;
3711556Srgrimes		case 'w':
3721556Srgrimes			if (wflag)
3731556Srgrimes				termwidth = UNLIMITED;
3741556Srgrimes			else if (termwidth < 131)
3751556Srgrimes				termwidth = 131;
3761556Srgrimes			wflag++;
3771556Srgrimes			break;
378127499Sgad		case 'X':
379127499Sgad			/*
380127499Sgad			 * Note that `-X' and `-x' are not standard "selector"
381127499Sgad			 * options. For most selector-options, we check *all*
382127499Sgad			 * processes to see if any are matched by the given
383127499Sgad			 * value(s).  After we have a set of all the matched
384127499Sgad			 * processes, then `-X' and `-x' govern whether we
385127499Sgad			 * modify that *matched* set for processes which do
386127499Sgad			 * not have a controlling terminal.  `-X' causes
387127499Sgad			 * those processes to be deleted from the matched
388127499Sgad			 * set, while `-x' causes them to be kept.
389127499Sgad			 */
390127499Sgad			xkeep = 0;
391127499Sgad			break;
3921556Srgrimes		case 'x':
393127499Sgad			xkeep = 1;
3941556Srgrimes			break;
39586922Sgreen		case 'Z':
396109502Sjmallett			parsefmt(Zfmt, 0);
39786922Sgreen			Zfmt[0] = '\0';
39886922Sgreen			break;
3991556Srgrimes		case '?':
4001556Srgrimes		default:
4011556Srgrimes			usage();
4021556Srgrimes		}
4031556Srgrimes	argc -= optind;
4041556Srgrimes	argv += optind;
405129914Sgad
406129914Sgad	/*
407129914Sgad	 * If there arguments after processing all the options, attempt
408129914Sgad	 * to treat them as a list of process ids.
409129914Sgad	 */
410129914Sgad	while (*argv) {
411129914Sgad		if (!isdigitch(**argv))
412129914Sgad			break;
413129914Sgad		add_list(&pidlist, *argv);
414129914Sgad		argv++;
415129914Sgad	}
416129914Sgad	if (*argv) {
417129914Sgad		fprintf(stderr, "%s: illegal argument: %s\n",
418129914Sgad		    getprogname(), *argv);
419129914Sgad		usage();
420129914Sgad	}
421127499Sgad	if (optfatal)
422127542Sgad		exit(1);		/* Error messages already printed. */
423127542Sgad	if (xkeep < 0)			/* Neither -X nor -x was specified. */
424127499Sgad		xkeep = xkeep_implied;
425127499Sgad
426129914Sgad
4271556Srgrimes	/*
4281556Srgrimes	 * Discard setgid privileges if not the running kernel so that bad
4291556Srgrimes	 * guys can't print interesting stuff from kernel memory.
4301556Srgrimes	 */
431129967Sgad	if (dropgid)
4321556Srgrimes		setgid(getgid());
4331556Srgrimes
43489909Sru	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
4351556Srgrimes	if (kd == 0)
4361556Srgrimes		errx(1, "%s", errbuf);
4371556Srgrimes
43890143Smarkm	if (!_fmt)
439109502Sjmallett		parsefmt(dfmt, 0);
4401556Srgrimes
441127499Sgad	if (nselectors == 0) {
442127823Sgad		uidlist.l.ptr = malloc(sizeof(uid_t));
443127823Sgad		if (uidlist.l.ptr == NULL)
44497877Sjmallett			errx(1, "malloc failed");
445127499Sgad		nselectors = 1;
446127499Sgad		uidlist.count = uidlist.maxcount = 1;
447127823Sgad		*uidlist.l.uids = getuid();
44866377Sbrian	}
4491556Srgrimes
4501556Srgrimes	/*
4511556Srgrimes	 * scan requested variables, noting what structures are needed,
45253170Skris	 * and adjusting header widths as appropriate.
4531556Srgrimes	 */
4541556Srgrimes	scanvars();
455127499Sgad
4561556Srgrimes	/*
457127499Sgad	 * Get process list.  If the user requested just one selector-
458127499Sgad	 * option, then kvm_getprocs can be asked to return just those
459127499Sgad	 * processes.  Otherwise, have it return all processes, and
460127499Sgad	 * then this routine will search that full list and select the
461127499Sgad	 * processes which match any of the user's selector-options.
4621556Srgrimes	 */
463127499Sgad	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
464127499Sgad	flag = 0;
465127499Sgad	if (nselectors == 1) {
466129600Sgad		if (gidlist.count == 1) {
467129600Sgad			what = KERN_PROC_RGID | showthreads;
468129600Sgad			flag = *gidlist.l.gids;
469129600Sgad			nselectors = 0;
470129600Sgad		} else if (pgrplist.count == 1) {
471127499Sgad			what = KERN_PROC_PGRP | showthreads;
472127823Sgad			flag = *pgrplist.l.pids;
473127499Sgad			nselectors = 0;
474127499Sgad		} else if (pidlist.count == 1) {
475127499Sgad			what = KERN_PROC_PID | showthreads;
476127823Sgad			flag = *pidlist.l.pids;
477127499Sgad			nselectors = 0;
478127499Sgad		} else if (ruidlist.count == 1) {
479127499Sgad			what = KERN_PROC_RUID | showthreads;
480127823Sgad			flag = *ruidlist.l.uids;
481127499Sgad			nselectors = 0;
482127499Sgad		} else if (sesslist.count == 1) {
483127499Sgad			what = KERN_PROC_SESSION | showthreads;
484127823Sgad			flag = *sesslist.l.pids;
485127499Sgad			nselectors = 0;
486127499Sgad		} else if (ttylist.count == 1) {
487127499Sgad			what = KERN_PROC_TTY | showthreads;
488127823Sgad			flag = *ttylist.l.ttys;
489127499Sgad			nselectors = 0;
490127499Sgad		} else if (uidlist.count == 1) {
491127499Sgad			what = KERN_PROC_UID | showthreads;
492127823Sgad			flag = *uidlist.l.uids;
493127499Sgad			nselectors = 0;
494127499Sgad		} else if (all) {
495127499Sgad			/* No need for this routine to select processes. */
496127499Sgad			nselectors = 0;
497127499Sgad		}
4981556Srgrimes	}
499126127Sdeischen
5001556Srgrimes	/*
5011556Srgrimes	 * select procs
5021556Srgrimes	 */
503127499Sgad	nentries = -1;
504127149Sgad	kp = kvm_getprocs(kd, what, flag, &nentries);
505127544Sgad	if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
5061556Srgrimes		errx(1, "%s", kvm_geterr(kd));
507127499Sgad	nkept = 0;
508127149Sgad	if (nentries > 0) {
509127149Sgad		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
510127149Sgad			errx(1, "malloc failed");
511127149Sgad		for (i = nentries; --i >= 0; ++kp) {
512127499Sgad			/*
513127499Sgad			 * If the user specified multiple selection-criteria,
514127499Sgad			 * then keep any process matched by the inclusive OR
515127499Sgad			 * of all the selection-criteria given.
516127499Sgad			 */
517127499Sgad			if (pidlist.count > 0) {
518127499Sgad				for (elem = 0; elem < pidlist.count; elem++)
519127823Sgad					if (kp->ki_pid == pidlist.l.pids[elem])
520127499Sgad						goto keepit;
521127499Sgad			}
522127499Sgad			/*
523127499Sgad			 * Note that we had to process pidlist before
524127499Sgad			 * filtering out processes which do not have
525127499Sgad			 * a controlling terminal.
526127499Sgad			 */
527127499Sgad			if (xkeep == 0) {
528127499Sgad				if ((kp->ki_tdev == NODEV ||
529127499Sgad				    (kp->ki_flag & P_CONTROLT) == 0))
530127499Sgad					continue;
531127499Sgad			}
532127499Sgad			if (nselectors == 0)
533127499Sgad				goto keepit;
534127499Sgad			if (gidlist.count > 0) {
535127499Sgad				for (elem = 0; elem < gidlist.count; elem++)
536127823Sgad					if (kp->ki_rgid == gidlist.l.gids[elem])
537127499Sgad						goto keepit;
538127499Sgad			}
539127499Sgad			if (pgrplist.count > 0) {
540127499Sgad				for (elem = 0; elem < pgrplist.count; elem++)
541127823Sgad					if (kp->ki_pgid ==
542127823Sgad					    pgrplist.l.pids[elem])
543127499Sgad						goto keepit;
544127499Sgad			}
545127499Sgad			if (ruidlist.count > 0) {
546127499Sgad				for (elem = 0; elem < ruidlist.count; elem++)
547127823Sgad					if (kp->ki_ruid ==
548127823Sgad					    ruidlist.l.uids[elem])
549127499Sgad						goto keepit;
550127499Sgad			}
551127499Sgad			if (sesslist.count > 0) {
552127499Sgad				for (elem = 0; elem < sesslist.count; elem++)
553127823Sgad					if (kp->ki_sid == sesslist.l.pids[elem])
554127499Sgad						goto keepit;
555127499Sgad			}
556127499Sgad			if (ttylist.count > 0) {
557127499Sgad				for (elem = 0; elem < ttylist.count; elem++)
558127823Sgad					if (kp->ki_tdev == ttylist.l.ttys[elem])
559127499Sgad						goto keepit;
560127499Sgad			}
561127499Sgad			if (uidlist.count > 0) {
562127499Sgad				for (elem = 0; elem < uidlist.count; elem++)
563127823Sgad					if (kp->ki_uid == uidlist.l.uids[elem])
564127499Sgad						goto keepit;
565127499Sgad			}
566127499Sgad			/*
567127499Sgad			 * This process did not match any of the user's
568127499Sgad			 * selector-options, so skip the process.
569127499Sgad			 */
570127499Sgad			continue;
571127499Sgad
572127499Sgad		keepit:
573130816Sgad			next_KINFO = &kinfo[nkept];
574130816Sgad			next_KINFO->ki_p = kp;
575130816Sgad			next_KINFO->ki_pcpu = getpcpu(next_KINFO);
576130816Sgad			if (sortby == SORTMEM)
577130816Sgad				next_KINFO->ki_memsize = kp->ki_tsize +
578130816Sgad				    kp->ki_dsize + kp->ki_ssize;
579127149Sgad			if (needuser)
580130816Sgad				saveuser(next_KINFO);
581130816Sgad			dynsizevars(next_KINFO);
582127499Sgad			nkept++;
583127149Sgad		}
5841556Srgrimes	}
58525271Sjkh
58625271Sjkh	sizevars();
58725271Sjkh
5881556Srgrimes	/*
5891556Srgrimes	 * print header
5901556Srgrimes	 */
5911556Srgrimes	printheader();
592127499Sgad	if (nkept == 0)
59362803Swill		exit(1);
594127499Sgad
5951556Srgrimes	/*
5961556Srgrimes	 * sort proc list
5971556Srgrimes	 */
598127499Sgad	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
5991556Srgrimes	/*
600127499Sgad	 * For each process, call each variable output function.
6011556Srgrimes	 */
602127499Sgad	for (i = lineno = 0; i < nkept; i++) {
603130999Sgad		STAILQ_FOREACH(vent, &varlist, next_ve) {
6041556Srgrimes			(vent->var->oproc)(&kinfo[i], vent);
605130999Sgad			if (STAILQ_NEXT(vent, next_ve) != NULL)
6061556Srgrimes				(void)putchar(' ');
6071556Srgrimes		}
6081556Srgrimes		(void)putchar('\n');
6091556Srgrimes		if (prtheader && lineno++ == prtheader - 4) {
6101556Srgrimes			(void)putchar('\n');
6111556Srgrimes			printheader();
6121556Srgrimes			lineno = 0;
6131556Srgrimes		}
6141556Srgrimes	}
615127499Sgad	free_list(&gidlist);
616127499Sgad	free_list(&pidlist);
617127499Sgad	free_list(&pgrplist);
618127499Sgad	free_list(&ruidlist);
619127499Sgad	free_list(&sesslist);
620127499Sgad	free_list(&ttylist);
621127499Sgad	free_list(&uidlist);
62266377Sbrian
6231556Srgrimes	exit(eval);
6241556Srgrimes}
6251556Srgrimes
626127499Sgadstatic int
627127499Sgadaddelem_gid(struct listinfo *inf, const char *elem)
628127499Sgad{
629127499Sgad	struct group *grp;
630127499Sgad	const char *nameorID;
631127499Sgad	char *endp;
632127602Sgad	u_long bigtemp;
633127499Sgad
634127499Sgad	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
635127499Sgad		if (*elem == '\0')
636127499Sgad			warnx("Invalid (zero-length) %s name", inf->lname);
637127499Sgad		else
638127499Sgad			warnx("%s name too long: %s", inf->lname, elem);
639127499Sgad		optfatal = 1;
640127542Sgad		return (0);		/* Do not add this value. */
641127499Sgad	}
642127499Sgad
643127499Sgad	/*
644127499Sgad	 * SUSv3 states that `ps -G grouplist' should match "real-group
645127499Sgad	 * ID numbers", and does not mention group-names.  I do want to
646127499Sgad	 * also support group-names, so this tries for a group-id first,
647127499Sgad	 * and only tries for a name if that doesn't work.  This is the
648127499Sgad	 * opposite order of what is done in addelem_uid(), but in
649127499Sgad	 * practice the order would only matter for group-names which
650127499Sgad	 * are all-numeric.
651127499Sgad	 */
652127499Sgad	grp = NULL;
653127499Sgad	nameorID = "named";
654127499Sgad	errno = 0;
655127602Sgad	bigtemp = strtoul(elem, &endp, 10);
656127602Sgad	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
657127499Sgad		nameorID = "name or ID matches";
658127602Sgad		grp = getgrgid((gid_t)bigtemp);
659127499Sgad	}
660127499Sgad	if (grp == NULL)
661127499Sgad		grp = getgrnam(elem);
662127499Sgad	if (grp == NULL) {
663127499Sgad		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
664127499Sgad		optfatal = 1;
665129967Sgad		return (0);
666127499Sgad	}
667127499Sgad	if (inf->count >= inf->maxcount)
668127499Sgad		expand_list(inf);
669127823Sgad	inf->l.gids[(inf->count)++] = grp->gr_gid;
670127499Sgad	return (1);
671127499Sgad}
672127499Sgad
673127597Sgad#define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h. */
674127499Sgadstatic int
675127499Sgadaddelem_pid(struct listinfo *inf, const char *elem)
676127149Sgad{
677127539Sgad	char *endp;
678127149Sgad	long tempid;
679127149Sgad
680129917Sgad	if (*elem == '\0') {
681129917Sgad		warnx("Invalid (zero-length) process id");
682129917Sgad		optfatal = 1;
683129917Sgad		return (0);		/* Do not add this value. */
684127149Sgad	}
685127149Sgad
686129952Sgad	errno = 0;
687129952Sgad	tempid = strtol(elem, &endp, 10);
688129952Sgad	if (*endp != '\0' || tempid < 0 || elem == endp) {
689129952Sgad		warnx("Invalid %s: %s", inf->lname, elem);
690129952Sgad		errno = ERANGE;
691129952Sgad	} else if (errno != 0 || tempid > BSD_PID_MAX) {
692129952Sgad		warnx("%s too large: %s", inf->lname, elem);
693129952Sgad		errno = ERANGE;
694129952Sgad	}
695129952Sgad	if (errno == ERANGE) {
696129952Sgad		optfatal = 1;
697129967Sgad		return (0);
698129952Sgad	}
699127499Sgad	if (inf->count >= inf->maxcount)
700127499Sgad		expand_list(inf);
701127823Sgad	inf->l.pids[(inf->count)++] = tempid;
702127499Sgad	return (1);
703127499Sgad}
704127499Sgad#undef	BSD_PID_MAX
705127149Sgad
706127499Sgadstatic int
707127499Sgadaddelem_tty(struct listinfo *inf, const char *elem)
708127499Sgad{
709127539Sgad	const char *ttypath;
710127539Sgad	struct stat sb;
711127499Sgad	char pathbuf[PATH_MAX];
712127499Sgad
713127499Sgad	if (strcmp(elem, "co") == 0)
714127499Sgad		ttypath = strdup(_PATH_CONSOLE);
715127499Sgad	else if (*elem == '/')
716127499Sgad		ttypath = elem;
717127499Sgad	else {
718127499Sgad		strlcpy(pathbuf, _PATH_TTY, sizeof(pathbuf));
719127499Sgad		strlcat(pathbuf, elem, sizeof(pathbuf));
720127499Sgad		ttypath = pathbuf;
721127499Sgad	}
722127499Sgad
723127499Sgad	if (stat(ttypath, &sb) == -1) {
724127499Sgad		warn("%s", ttypath);
725127499Sgad		optfatal = 1;
726129967Sgad		return (0);
727127499Sgad	}
728127499Sgad	if (!S_ISCHR(sb.st_mode)) {
729127499Sgad		warn("%s: Not a terminal", ttypath);
730127499Sgad		optfatal = 1;
731129967Sgad		return (0);
732127499Sgad	}
733127499Sgad	if (inf->count >= inf->maxcount)
734127499Sgad		expand_list(inf);
735127823Sgad	inf->l.ttys[(inf->count)++] = sb.st_rdev;
736127499Sgad	return (1);
737127149Sgad}
738127149Sgad
739127499Sgadstatic int
740127499Sgadaddelem_uid(struct listinfo *inf, const char *elem)
74166377Sbrian{
74266377Sbrian	struct passwd *pwd;
743127539Sgad	char *endp;
744127602Sgad	u_long bigtemp;
74566377Sbrian
746127499Sgad	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
747127499Sgad		if (*elem == '\0')
748127499Sgad			warnx("Invalid (zero-length) %s name", inf->lname);
749127499Sgad		else
750127499Sgad			warnx("%s name too long: %s", inf->lname, elem);
751127499Sgad		optfatal = 1;
752127542Sgad		return (0);		/* Do not add this value. */
753127499Sgad	}
75466377Sbrian
755127499Sgad	pwd = getpwnam(elem);
756127499Sgad	if (pwd == NULL) {
757127499Sgad		errno = 0;
758127602Sgad		bigtemp = strtoul(elem, &endp, 10);
759127602Sgad		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
760127499Sgad			warnx("No %s named '%s'", inf->lname, elem);
761127499Sgad		else {
762127499Sgad			/* The string is all digits, so it might be a userID. */
763127602Sgad			pwd = getpwuid((uid_t)bigtemp);
764127499Sgad			if (pwd == NULL)
765127499Sgad				warnx("No %s name or ID matches '%s'",
766127499Sgad				    inf->lname, elem);
76766377Sbrian		}
768127499Sgad	}
769127499Sgad	if (pwd == NULL) {
770127509Sgad		/*
771127509Sgad		 * These used to be treated as minor warnings (and the
772127509Sgad		 * option was simply ignored), but now they are fatal
773127509Sgad		 * errors (and the command will be aborted).
774127509Sgad		 */
775127509Sgad		optfatal = 1;
776129967Sgad		return (0);
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)
793129967Sgad		inf->addelem(inf, elemcopy);
794127499Sgad	while (*argp != '\0') {
795127499Sgad		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
796127499Sgad			argp++;
797127499Sgad		savep = argp;
798127499Sgad		toolong = 0;
799127499Sgad		cp = elemcopy;
800127499Sgad		if (strchr(T_SEP, *argp) == NULL) {
801127499Sgad			endp = elemcopy + sizeof(elemcopy) - 1;
802127499Sgad			while (*argp != '\0' && cp <= endp &&
803127499Sgad			    strchr(W_SEP T_SEP, *argp) == NULL)
804127499Sgad				*cp++ = *argp++;
805127499Sgad			if (cp > endp)
806127499Sgad				toolong = 1;
80766377Sbrian		}
808127499Sgad		if (!toolong) {
809127499Sgad			*cp = '\0';
810127542Sgad			/*
811129953Sgad			 * Add this single element to the given list.
812127542Sgad			 */
813127499Sgad			inf->addelem(inf, elemcopy);
814127499Sgad		} else {
815127499Sgad			/*
816127499Sgad			 * The string is too long to copy.  Find the end
817127499Sgad			 * of the string to print out the warning message.
818127499Sgad			 */
819127499Sgad			while (*argp != '\0' && strchr(W_SEP T_SEP,
820127499Sgad			    *argp) == NULL)
821127499Sgad				argp++;
822127499Sgad			warnx("Value too long: %.*s", (int)(argp - savep),
823127499Sgad			    savep);
824127499Sgad			optfatal = 1;
82566377Sbrian		}
826127499Sgad		/*
827127499Sgad		 * Skip over any number of trailing whitespace characters,
828127499Sgad		 * but only one (at most) trailing element-terminating
829127499Sgad		 * character.
830127499Sgad		 */
831127499Sgad		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
832127499Sgad			argp++;
833127499Sgad		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
834127499Sgad			argp++;
835127499Sgad			/* Catch case where string ended with a comma. */
836127499Sgad			if (*argp == '\0')
837127499Sgad				inf->addelem(inf, argp);
838127499Sgad		}
83966377Sbrian	}
840127499Sgad}
84166377Sbrian
842127499Sgadstatic void *
843127499Sgadexpand_list(struct listinfo *inf)
844127499Sgad{
845127539Sgad	void *newlist;
846127499Sgad	int newmax;
84766377Sbrian
848127499Sgad	newmax = (inf->maxcount + 1) << 1;
849127823Sgad	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
850127499Sgad	if (newlist == NULL) {
851127823Sgad		free(inf->l.ptr);
852129967Sgad		errx(1, "realloc to %d %ss failed", newmax, inf->lname);
853127499Sgad	}
854127499Sgad	inf->maxcount = newmax;
855127823Sgad	inf->l.ptr = newlist;
856127499Sgad
857127499Sgad	return (newlist);
85866377Sbrian}
85966377Sbrian
860127499Sgadstatic void
861127499Sgadfree_list(struct listinfo *inf)
862127499Sgad{
863127499Sgad
864127499Sgad	inf->count = inf->elemsize = inf->maxcount = 0;
865127823Sgad	if (inf->l.ptr != NULL)
866127823Sgad		free(inf->l.ptr);
867127499Sgad	inf->addelem = NULL;
868127499Sgad	inf->lname = NULL;
869127823Sgad	inf->l.ptr = NULL;
870127499Sgad}
871127499Sgad
872127499Sgadstatic void
873127499Sgadinit_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
874127499Sgad    const char *lname)
875127499Sgad{
876127499Sgad
877127499Sgad	inf->count = inf->maxcount = 0;
878127499Sgad	inf->elemsize = elemsize;
879127499Sgad	inf->addelem = artn;
880127499Sgad	inf->lname = lname;
881127823Sgad	inf->l.ptr = NULL;
882127499Sgad}
883127499Sgad
884109502SjmallettVARENT *
885109502Sjmallettfind_varentry(VAR *v)
886109502Sjmallett{
887109502Sjmallett	struct varent *vent;
888109502Sjmallett
889130999Sgad	STAILQ_FOREACH(vent, &varlist, next_ve) {
890109502Sjmallett		if (strcmp(vent->var->name, v->name) == 0)
891109502Sjmallett			return vent;
892109502Sjmallett	}
893109502Sjmallett	return NULL;
894109502Sjmallett}
895109502Sjmallett
8961556Srgrimesstatic void
89790110Simpscanvars(void)
8981556Srgrimes{
8991556Srgrimes	struct varent *vent;
9001556Srgrimes	VAR *v;
90125271Sjkh
902130999Sgad	STAILQ_FOREACH(vent, &varlist, next_ve) {
90325271Sjkh		v = vent->var;
90425271Sjkh		if (v->flag & DSIZ) {
90525271Sjkh			v->dwidth = v->width;
90625271Sjkh			v->width = 0;
90725271Sjkh		}
90825271Sjkh		if (v->flag & USER)
90925271Sjkh			needuser = 1;
91025271Sjkh		if (v->flag & COMM)
91125271Sjkh			needcomm = 1;
91225271Sjkh	}
91325271Sjkh}
91425271Sjkh
91525271Sjkhstatic void
91690110Simpdynsizevars(KINFO *ki)
91725271Sjkh{
91825271Sjkh	struct varent *vent;
91925271Sjkh	VAR *v;
9201556Srgrimes	int i;
9211556Srgrimes
922130999Sgad	STAILQ_FOREACH(vent, &varlist, next_ve) {
9231556Srgrimes		v = vent->var;
92425271Sjkh		if (!(v->flag & DSIZ))
92525271Sjkh			continue;
92625271Sjkh		i = (v->sproc)( ki);
92725271Sjkh		if (v->width < i)
92825271Sjkh			v->width = i;
92925271Sjkh		if (v->width > v->dwidth)
93025271Sjkh			v->width = v->dwidth;
93125271Sjkh	}
93225271Sjkh}
93325271Sjkh
93425271Sjkhstatic void
93590110Simpsizevars(void)
93625271Sjkh{
93725271Sjkh	struct varent *vent;
93825271Sjkh	VAR *v;
93925271Sjkh	int i;
94025271Sjkh
941130999Sgad	STAILQ_FOREACH(vent, &varlist, next_ve) {
94225271Sjkh		v = vent->var;
943109504Sjmallett		i = strlen(vent->header);
9441556Srgrimes		if (v->width < i)
9451556Srgrimes			v->width = i;
9461556Srgrimes		totwidth += v->width + 1;	/* +1 for space */
9471556Srgrimes	}
9481556Srgrimes	totwidth--;
9491556Srgrimes}
9501556Srgrimes
95190143Smarkmstatic const char *
95290110Simpfmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
953127542Sgad    char *comm, int maxlen)
9541556Srgrimes{
95590143Smarkm	const char *s;
9561556Srgrimes
95790143Smarkm	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
9581556Srgrimes	return (s);
9591556Srgrimes}
9601556Srgrimes
96171578Sjhb#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
96231552Sdyson
9631556Srgrimesstatic void
96490110Simpsaveuser(KINFO *ki)
9651556Srgrimes{
9661556Srgrimes
96771578Sjhb	if (ki->ki_p->ki_sflag & PS_INMEM) {
9681556Srgrimes		/*
9691556Srgrimes		 * The u-area might be swapped out, and we can't get
9701556Srgrimes		 * at it because we have a crashdump and no swap.
9711556Srgrimes		 * If it's here fill in these fields, otherwise, just
9721556Srgrimes		 * leave them 0.
9731556Srgrimes		 */
97469896Smckusick		ki->ki_valid = 1;
9751556Srgrimes	} else
97669896Smckusick		ki->ki_valid = 0;
9771556Srgrimes	/*
9781556Srgrimes	 * save arguments if needed
9791556Srgrimes	 */
980130991Sgad	if (needcomm) {
981130991Sgad		if (ki->ki_p->ki_stat == SZOMB)
982130991Sgad			ki->ki_args = strdup("<defunct>");
983130991Sgad		else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
984130991Sgad			ki->ki_args = strdup(fmt(kvm_getargv, ki,
985130991Sgad			    ki->ki_p->ki_comm, MAXCOMLEN));
986130991Sgad		else
987130991Sgad			asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
988130991Sgad		if (ki->ki_env == NULL)
989130991Sgad			errx(1, "malloc failed");
99053276Speter	} else {
99153276Speter		ki->ki_args = NULL;
99253276Speter	}
993130991Sgad	if (needenv) {
994130991Sgad		if (UREADOK(ki))
995130991Sgad			ki->ki_env = strdup(fmt(kvm_getenvv, ki,
996130991Sgad			    (char *)NULL, 0));
997130991Sgad		else
998130991Sgad			ki->ki_env = strdup("()");
999130991Sgad		if (ki->ki_env == NULL)
1000130991Sgad			errx(1, "malloc failed");
100153276Speter	} else {
100253276Speter		ki->ki_env = NULL;
100353276Speter	}
10041556Srgrimes}
10051556Srgrimes
1006130816Sgad/* A macro used to improve the readability of pscomp(). */
1007130816Sgad#define	DIFF_RETURN(a, b, field) do {	\
1008130816Sgad	if ((a)->field != (b)->field)	\
1009130816Sgad		return (((a)->field < (b)->field) ? -1 : 1); 	\
1010130816Sgad} while (0)
1011130816Sgad
10121556Srgrimesstatic int
101390110Simppscomp(const void *a, const void *b)
10141556Srgrimes{
1015127596Sgad	const KINFO *ka, *kb;
10161556Srgrimes
1017127596Sgad	ka = a;
1018127596Sgad	kb = b;
1019127596Sgad	/* SORTCPU and SORTMEM are sorted in descending order. */
1020130816Sgad	if (sortby == SORTCPU)
1021130816Sgad		DIFF_RETURN(kb, ka, ki_pcpu);
1022130816Sgad	if (sortby == SORTMEM)
1023130816Sgad		DIFF_RETURN(kb, ka, ki_memsize);
1024127596Sgad	/*
1025127596Sgad	 * TTY's are sorted in ascending order, except that all NODEV
1026127596Sgad	 * processes come before all processes with a device.
1027127596Sgad	 */
1028130816Sgad	if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1029130816Sgad		if (ka->ki_p->ki_tdev == NODEV)
1030130816Sgad			return (-1);
1031130816Sgad		if (kb->ki_p->ki_tdev == NODEV)
1032130816Sgad			return (1);
1033130816Sgad		DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1034130816Sgad	}
1035130816Sgad
1036130972Sgad	/* PID's and TID's (threads) are sorted in ascending order. */
1037130816Sgad	DIFF_RETURN(ka, kb, ki_p->ki_pid);
1038130972Sgad	DIFF_RETURN(ka, kb, ki_p->ki_tid);
1039127596Sgad	return (0);
10401556Srgrimes}
1041130816Sgad#undef DIFF_RETURN
10421556Srgrimes
10431556Srgrimes/*
10441556Srgrimes * ICK (all for getopt), would rather hide the ugliness
10451556Srgrimes * here than taint the main code.
10461556Srgrimes *
10471556Srgrimes *  ps foo -> ps -foo
10481556Srgrimes *  ps 34 -> ps -p34
10491556Srgrimes *
10501556Srgrimes * The old convention that 't' with no trailing tty arg means the users
10511556Srgrimes * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
10521556Srgrimes * feature is available with the option 'T', which takes no argument.
10531556Srgrimes */
10541556Srgrimesstatic char *
1055129915Sgadkludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
10561556Srgrimes{
10571556Srgrimes	size_t len;
1058129914Sgad	char *argp, *cp, *newopts, *ns, *optp, *pidp;
10591556Srgrimes
1060102886Sjmallett	/*
1061129914Sgad	 * See if the original value includes any option which takes an
1062129914Sgad	 * argument (and will thus use up the remainder of the string).
1063102886Sjmallett	 */
1064129914Sgad	argp = NULL;
1065129914Sgad	if (optlist != NULL) {
1066129914Sgad		for (cp = origval; *cp != '\0'; cp++) {
1067129914Sgad			optp = strchr(optlist, *cp);
1068129914Sgad			if ((optp != NULL) && *(optp + 1) == ':') {
1069129914Sgad				argp = cp;
1070129914Sgad				break;
1071129914Sgad			}
1072129914Sgad		}
1073129914Sgad	}
1074129914Sgad	if (argp != NULL && *origval == '-')
1075129914Sgad		return (origval);
1076102886Sjmallett
10771556Srgrimes	/*
10781556Srgrimes	 * if last letter is a 't' flag with no argument (in the context
10791556Srgrimes	 * of the oldps options -- option string NOT starting with a '-' --
10801556Srgrimes	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
108181743Sbrian	 *
1082129634Sgad	 * However, if a flag accepting a string argument is found earlier
1083129634Sgad	 * in the option string (including a possible `t' flag), then the
1084129634Sgad	 * remainder of the string must be the argument to that flag; so
1085129914Sgad	 * do not modify that argument.  Note that a trailing `t' would
1086129914Sgad	 * cause argp to be set, if argp was not already set by some
1087129914Sgad	 * earlier option.
10881556Srgrimes	 */
1089129914Sgad	len = strlen(origval);
1090129914Sgad	cp = origval + len - 1;
1091129914Sgad	pidp = NULL;
1092129915Sgad	if (*cp == 't' && *origval != '-' && cp == argp) {
1093129915Sgad		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1094129915Sgad			*cp = 'T';
1095129915Sgad	} else if (argp == NULL) {
10961556Srgrimes		/*
1097129914Sgad		 * The original value did not include any option which takes
1098129914Sgad		 * an argument (and that would include `p' and `t'), so check
1099129914Sgad		 * the value for trailing number, or comma-separated list of
1100129914Sgad		 * numbers, which we will treat as a pid request.
11011556Srgrimes		 */
1102129914Sgad		if (isdigitch(*cp)) {
1103129914Sgad			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1104129914Sgad				--cp;
1105129914Sgad			pidp = cp + 1;
1106129914Sgad		}
11071556Srgrimes	}
1108129914Sgad
11091556Srgrimes	/*
1110129914Sgad	 * If nothing needs to be added to the string, then return
1111129914Sgad	 * the "original" (although possibly modified) value.
11121556Srgrimes	 */
1113129914Sgad	if (*origval == '-' && pidp == NULL)
1114129914Sgad		return (origval);
1115129914Sgad
1116129914Sgad	/*
1117129914Sgad	 * Create a copy of the string to add '-' and/or 'p' to the
1118129914Sgad	 * original value.
1119129914Sgad	 */
1120129914Sgad	if ((newopts = ns = malloc(len + 3)) == NULL)
1121129914Sgad		errx(1, "malloc failed");
1122129914Sgad
1123129914Sgad	if (*origval != '-')
1124129914Sgad		*ns++ = '-';	/* add option flag */
1125129914Sgad
1126129914Sgad	if (pidp == NULL)
1127129914Sgad		strcpy(ns, origval);
1128129914Sgad	else {
1129129914Sgad		/*
1130129914Sgad		 * Copy everything before the pid string, add the `p',
1131129914Sgad		 * and then copy the pid string.
1132129914Sgad		 */
1133129914Sgad		len = pidp - origval;
1134129914Sgad		memcpy(ns, origval, len);
1135129914Sgad		ns += len;
11361556Srgrimes		*ns++ = 'p';
1137129914Sgad		strcpy(ns, pidp);
1138129914Sgad	}
11391556Srgrimes
11401556Srgrimes	return (newopts);
11411556Srgrimes}
11421556Srgrimes
11431556Srgrimesstatic void
114490110Simpusage(void)
11451556Srgrimes{
1146130973Sgad#define	SINGLE_OPTS	"[-aCc" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
11471556Srgrimes
1148127499Sgad	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1149127507Sgad	    "usage: ps " SINGLE_OPTS " [-G gid[,gid]] [-O|o fmt]",
1150127499Sgad	    "          [-p pid[,pid]] [-t tty[,tty]] [-U user[,user]]",
1151127499Sgad	    "          [-M core] [-N system]",
115226465Scharnier	    "       ps [-L]");
11531556Srgrimes	exit(1);
11541556Srgrimes}
1155