ps.c revision 129914
1113094Sphk/*-
2135482Sphk * Copyright (c) 1990, 1993, 1994
3113094Sphk *	The Regents of the University of California.  All rights reserved.
4113094Sphk *
5113094Sphk * Redistribution and use in source and binary forms, with or without
6113094Sphk * modification, are permitted provided that the following conditions
7113094Sphk * are met:
8113094Sphk * 1. Redistributions of source code must retain the above copyright
9113094Sphk *    notice, this list of conditions and the following disclaimer.
10113094Sphk * 2. Redistributions in binary form must reproduce the above copyright
11113094Sphk *    notice, this list of conditions and the following disclaimer in the
12113094Sphk *    documentation and/or other materials provided with the distribution.
13113094Sphk * 4. Neither the name of the University nor the names of its contributors
14113094Sphk *    may be used to endorse or promote products derived from this software
15113094Sphk *    without specific prior written permission.
16113094Sphk *
17113094Sphk * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18113094Sphk * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19113094Sphk * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20113094Sphk * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21113094Sphk * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22113094Sphk * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23113094Sphk * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24113094Sphk * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25113094Sphk * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26113094Sphk * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27113094Sphk * SUCH DAMAGE.
28135482Sphk * ------+---------+---------+-------- + --------+---------+---------+---------*
29135482Sphk * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
30135482Sphk * All rights reserved.
31135482Sphk *
32135482Sphk * Significant modifications made to bring `ps' options somewhat closer
33135482Sphk * to the standard for `ps' as described in SingleUnixSpec-v3.
34135482Sphk * ------+---------+---------+-------- + --------+---------+---------+---------*
35135482Sphk */
36135482Sphk
37135482Sphk#ifndef lint
38135482Sphkstatic const char copyright[] =
39135482Sphk"@(#) Copyright (c) 1990, 1993, 1994\n\
40135482Sphk	The Regents of the University of California.  All rights reserved.\n";
41135482Sphk#endif /* not lint */
42113094Sphk
43113094Sphk#if 0
44135482Sphk#ifndef lint
45119418Sobrienstatic char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
46119418Sobrien#endif /* not lint */
47119418Sobrien#endif
48113094Sphk
49113094Sphk#include <sys/cdefs.h>
50113094Sphk__FBSDID("$FreeBSD: head/bin/ps/ps.c 129914 2004-06-01 02:03:21Z gad $");
51113094Sphk
52130026Sphk#include <sys/param.h>
53113270Sphk#include <sys/proc.h>
54113094Sphk#include <sys/user.h>
55113094Sphk#include <sys/stat.h>
56113094Sphk#include <sys/ioctl.h>
57113094Sphk#include <sys/sysctl.h>
58113094Sphk
59119274Simp#include <ctype.h>
60119274Simp#include <err.h>
61113094Sphk#include <errno.h>
62113094Sphk#include <fcntl.h>
63113094Sphk#include <grp.h>
64113094Sphk#include <kvm.h>
65113270Sphk#include <limits.h>
66113270Sphk#include <locale.h>
67113270Sphk#include <paths.h>
68113270Sphk#include <pwd.h>
69135482Sphk#include <stdio.h>
70135482Sphk#include <stdlib.h>
71135482Sphk#include <string.h>
72135482Sphk#include <unistd.h>
73135482Sphk
74135482Sphk#include "ps.h"
75113270Sphk
76135482Sphk#define	W_SEP	" \t"		/* "Whitespace" list separators */
77135482Sphk#define	T_SEP	","		/* "Terminate-element" list separators */
78135482Sphk
79135482Sphk#ifdef LAZY_PS
80135482Sphk#define	DEF_UREAD	0
81135482Sphk#define	OPT_LAZY_f	"f"
82135482Sphk#else
83135482Sphk#define	DEF_UREAD	1	/* Always do the more-expensive read. */
84143844Sphk#define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
85135482Sphk#endif
86135482Sphk
87135482Sphk/*
88135482Sphk * isdigit is defined to work on an 'int', in the range 0 to 255, plus EOF.
89113270Sphk * Define a wrapper which can take 'char', either signed or unsigned.
90113270Sphk */
91143844Sphk#define	isdigitch(Anychar) isdigit(((int) Anychar) & 255)
92113270Sphk
93113270Sphkint	 cflag;			/* -c */
94113270Sphkint	 eval;			/* Exit value */
95135482Sphktime_t	 now;			/* Current time(3) value */
96143844Sphkint	 rawcpu;		/* -C */
97135482Sphkint	 sumrusage;		/* -S */
98135482Sphkint	 termwidth;		/* Width of the screen (0 == infinity). */
99135482Sphkint	 totwidth;		/* Calculated-width of requested variables. */
100113094Sphk
101113094Sphkstruct varent *vhead;
102113094Sphk
103113094Sphkstatic int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
104113094Sphkstatic kvm_t	*kd;
105150526Sphkstatic KINFO	*kinfo;
106135482Sphkstatic int	 needcomm;	/* -o "command" */
107113270Sphkstatic int	 needenv;	/* -e */
108135482Sphkstatic int	 needuser;	/* -o "user" */
109135482Sphkstatic int	 optfatal;	/* Fatal error parsing some list-option. */
110135482Sphk
111135482Sphkstatic enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
112135482Sphk
113143844Sphkstruct listinfo;
114135482Sphktypedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
115113094Sphk
116135482Sphkstruct listinfo {
117135482Sphk	int		 count;
118166901Spiso	int		 maxcount;
119113270Sphk	int		 elemsize;
120135482Sphk	addelem_rtn	*addelem;
121135482Sphk	const char	*lname;
122171717Skib	union {
123135482Sphk		gid_t	*gids;
124135482Sphk		pid_t	*pids;
125135482Sphk		dev_t	*ttys;
126135482Sphk		uid_t	*uids;
127113094Sphk		void	*ptr;
128166901Spiso	} l;
129135482Sphk};
130135482Sphk
131135482Sphkstatic int	 addelem_gid(struct listinfo *, const char *);
132135482Sphkstatic int	 addelem_pid(struct listinfo *, const char *);
133135482Sphkstatic int	 addelem_tty(struct listinfo *, const char *);
134113270Sphkstatic int	 addelem_uid(struct listinfo *, const char *);
135135482Sphkstatic void	 add_list(struct listinfo *, const char *);
136150526Sphkstatic void	 dynsizevars(KINFO *);
137135482Sphkstatic void	*expand_list(struct listinfo *);
138166901Spisostatic const char *
139150526Sphk		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
140113270Sphk		    KINFO *, char *, int);
141143844Sphkstatic void	 free_list(struct listinfo *);
142135482Sphkstatic void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
143143844Sphkstatic char	*kludge_oldps_options(const char *opts, char *);
144113270Sphkstatic int	 pscomp(const void *, const void *);
145150526Sphkstatic void	 saveuser(KINFO *);
146135482Sphkstatic void	 scanvars(void);
147135482Sphkstatic void	 sizevars(void);
148113094Sphkstatic void	 usage(void);
149135482Sphk
150135482Sphkstatic char dfmt[] = "pid,tt,state,time,command";
151166901Spisostatic char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
152113270Sphkstatic char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
153113270Sphk			"tt,time,command";
154135482Sphkstatic char   o1[] = "pid";
155135482Sphkstatic char   o2[] = "tt,state,time,command";
156143844Sphkstatic char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
157150526Sphkstatic char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
158150526Sphk			"%cpu,%mem,command";
159113270Sphkstatic char Zfmt[] = "label";
160166901Spiso
161113270Sphk#define	PS_ARGS	"AaCce" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
162113270Sphk
163113094Sphkint
164135482Sphkmain(int argc, char *argv[])
165113270Sphk{
166135482Sphk	struct listinfo gidlist, pgrplist, pidlist;
167135482Sphk	struct listinfo ruidlist, sesslist, ttylist, uidlist;
168135482Sphk	struct kinfo_proc *kp;
169135482Sphk	struct varent *vent;
170113270Sphk	struct winsize ws;
171135482Sphk	const char *nlistf, *memf;
172135482Sphk	char *cols;
173135482Sphk	int all, ch, dropgid, elem, flag, _fmt, i, lineno;
174135482Sphk	int nentries, nkept, nselectors;
175135482Sphk	int prtheader, showthreads, wflag, what, xkeep, xkeep_implied;
176135482Sphk	char errbuf[_POSIX2_LINE_MAX];
177113270Sphk
178135482Sphk	(void) setlocale(LC_ALL, "");
179135482Sphk	time(&now);			/* Used by routines in print.c. */
180135482Sphk
181135482Sphk	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
182135482Sphk		termwidth = atoi(cols);
183135482Sphk	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
184113270Sphk	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
185135482Sphk	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
186135482Sphk	     ws.ws_col == 0)
187113270Sphk		termwidth = 79;
188135482Sphk	else
189113270Sphk		termwidth = ws.ws_col - 1;
190113270Sphk
191113270Sphk	/*
192135482Sphk	 * Hide a number of option-processing kludges in a separate routine,
193113094Sphk	 * to support some historical BSD behaviors, such as `ps axu'.
194113094Sphk	 */
195113270Sphk	if (argc > 1)
196135482Sphk		argv[1] = kludge_oldps_options(PS_ARGS, argv[1]);
197135482Sphk
198143844Sphk	all = dropgid = _fmt = nselectors = optfatal = 0;
199135482Sphk	prtheader = showthreads = wflag = xkeep_implied = 0;
200113094Sphk	xkeep = -1;			/* Neither -x nor -X. */
201135482Sphk	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
202135482Sphk	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
203135482Sphk	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
204135482Sphk	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
205135482Sphk	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
206135482Sphk	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
207135482Sphk	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
208135482Sphk	memf = nlistf = _PATH_DEVNULL;
209135482Sphk	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
210135482Sphk		switch((char)ch) {
211135482Sphk		case 'A':
212135482Sphk			/*
213135482Sphk			 * Exactly the same as `-ax'.   This has been
214135482Sphk			 * added for compatability with SUSv3, but for
215135482Sphk			 * now it will not be described in the man page.
216135482Sphk			 */
217135482Sphk			nselectors++;
218135482Sphk			all = xkeep = 1;
219135482Sphk			break;
220135482Sphk		case 'a':
221135482Sphk			nselectors++;
222135482Sphk			all = 1;
223135482Sphk			break;
224135482Sphk		case 'C':
225135482Sphk			rawcpu = 1;
226135482Sphk			break;
227135482Sphk		case 'c':
228135482Sphk			cflag = 1;
229135482Sphk			break;
230135482Sphk		case 'e':			/* XXX set ufmt */
231135482Sphk			needenv = 1;
232135482Sphk			break;
233135482Sphk#ifdef LAZY_PS
234135482Sphk		case 'f':
235135482Sphk			if (getuid() == 0 || getgid() == 0)
236135482Sphk				forceuread = 1;
237135482Sphk			break;
238135482Sphk#endif
239135482Sphk		case 'G':
240113270Sphk			add_list(&gidlist, optarg);
241135482Sphk			xkeep_implied = 1;
242143844Sphk			nselectors++;
243135482Sphk			break;
244135482Sphk		case 'g':
245135482Sphk#if 0
246143844Sphk			/*-
247143844Sphk			 * XXX - This SUSv3 behavior is still under debate
248143844Sphk			 *	since it conflicts with the (undocumented)
249135482Sphk			 *	`-g' option.  So we skip it for now.
250135482Sphk			 */
251135482Sphk			add_list(&pgrplist, optarg);
252135482Sphk			xkeep_implied = 1;
253143844Sphk			nselectors++;
254143844Sphk			break;
255143844Sphk#else
256135482Sphk			/* The historical BSD-ish (from SunOS) behavior. */
257135482Sphk			break;			/* no-op */
258135482Sphk#endif
259135482Sphk		case 'H':
260135482Sphk			showthreads = KERN_PROC_INC_THREAD;
261135482Sphk			break;
262135482Sphk		case 'h':
263135482Sphk			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
264135482Sphk			break;
265135482Sphk		case 'j':
266135482Sphk			parsefmt(jfmt, 0);
267135482Sphk			_fmt = 1;
268135482Sphk			jfmt[0] = '\0';
269113094Sphk			break;
270135482Sphk		case 'L':
271135482Sphk			showkey();
272135482Sphk			exit(0);
273143844Sphk		case 'l':
274135482Sphk			parsefmt(lfmt, 0);
275135482Sphk			_fmt = 1;
276113270Sphk			lfmt[0] = '\0';
277135482Sphk			break;
278150526Sphk		case 'M':
279113270Sphk			memf = optarg;
280135482Sphk			dropgid = 1;
281150526Sphk			break;
282113270Sphk		case 'm':
283135482Sphk			sortby = SORTMEM;
284150526Sphk			break;
285113270Sphk		case 'N':
286135482Sphk			nlistf = optarg;
287150526Sphk			dropgid = 1;
288113270Sphk			break;
289135482Sphk		case 'O':
290150526Sphk			parsefmt(o1, 1);
291113270Sphk			parsefmt(optarg, 1);
292135482Sphk			parsefmt(o2, 1);
293150526Sphk			o1[0] = o2[0] = '\0';
294113270Sphk			_fmt = 1;
295135482Sphk			break;
296150526Sphk		case 'o':
297113270Sphk			parsefmt(optarg, 1);
298135482Sphk			_fmt = 1;
299150526Sphk			break;
300113270Sphk		case 'p':
301135482Sphk			add_list(&pidlist, optarg);
302135482Sphk			/*
303113094Sphk			 * Note: `-p' does not *set* xkeep, but any values
304135482Sphk			 * from pidlist are checked before xkeep is.  That
305135482Sphk			 * way they are always matched, even if the user
306143844Sphk			 * specifies `-X'.
307150526Sphk			 */
308150526Sphk			nselectors++;
309150526Sphk			break;
310150526Sphk#if 0
311113094Sphk		case 'R':
312135482Sphk			/*-
313150526Sphk			 * XXX - This un-standard option is still under
314113094Sphk			 *	debate.  This is what SUSv3 defines as
315135482Sphk			 *	the `-U' option, and while it would be
316135482Sphk			 *	nice to have, it could cause even more
317135482Sphk			 *	confusion to implement it as `-R'.
318135482Sphk			 */
319135482Sphk			add_list(&ruidlist, optarg);
320143844Sphk			xkeep_implied = 1;
321135482Sphk			nselectors++;
322135482Sphk			break;
323135482Sphk#endif
324135482Sphk		case 'r':
325135482Sphk			sortby = SORTCPU;
326135482Sphk			break;
327135482Sphk		case 'S':
328135482Sphk			sumrusage = 1;
329135482Sphk			break;
330135482Sphk#if 0
331135482Sphk		case 's':
332143844Sphk			/*-
333135482Sphk			 * XXX - This non-standard option is still under
334135482Sphk			 *	debate.  This *is* supported on Solaris,
335135482Sphk			 *	Linux, and IRIX, but conflicts with `-s'
336135482Sphk			 *	on NetBSD and maybe some older BSD's.
337135482Sphk			 */
338135482Sphk			add_list(&sesslist, optarg);
339135482Sphk			xkeep_implied = 1;
340113270Sphk			nselectors++;
341135482Sphk			break;
342113270Sphk#endif
343113270Sphk		case 'T':
344113094Sphk			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
345113094Sphk				errx(1, "stdin: not a terminal");
346113094Sphk			/* FALLTHROUGH */
347113094Sphk		case 't':
348113094Sphk			add_list(&ttylist, optarg);
349113094Sphk			xkeep_implied = 1;
350113094Sphk			nselectors++;
351113094Sphk			break;
352113094Sphk		case 'U':
353143168Simp			/* This is what SUSv3 defines as the `-u' option. */
354113094Sphk			add_list(&uidlist, optarg);
355113094Sphk			xkeep_implied = 1;
356150526Sphk			nselectors++;
357150526Sphk			break;
358150526Sphk		case 'u':
359150526Sphk			parsefmt(ufmt, 0);
360150526Sphk			sortby = SORTCPU;
361150526Sphk			_fmt = 1;
362150526Sphk			ufmt[0] = '\0';
363113094Sphk			break;
364113094Sphk		case 'v':
365113094Sphk			parsefmt(vfmt, 0);
366113094Sphk			sortby = SORTMEM;
367150526Sphk			_fmt = 1;
368113094Sphk			vfmt[0] = '\0';
369113094Sphk			break;
370113094Sphk		case 'w':
371113094Sphk			if (wflag)
372113094Sphk				termwidth = UNLIMITED;
373150526Sphk			else if (termwidth < 131)
374150526Sphk				termwidth = 131;
375150526Sphk			wflag++;
376113094Sphk			break;
377166901Spiso		case 'X':
378150526Sphk			/*
379166901Spiso			 * Note that `-X' and `-x' are not standard "selector"
380166901Spiso			 * options. For most selector-options, we check *all*
381113270Sphk			 * processes to see if any are matched by the given
382113270Sphk			 * value(s).  After we have a set of all the matched
383150526Sphk			 * processes, then `-X' and `-x' govern whether we
384135482Sphk			 * modify that *matched* set for processes which do
385166901Spiso			 * not have a controlling terminal.  `-X' causes
386113270Sphk			 * those processes to be deleted from the matched
387113094Sphk			 * set, while `-x' causes them to be kept.
388150526Sphk			 */
389150526Sphk			xkeep = 0;
390113094Sphk			break;
391150526Sphk		case 'x':
392113094Sphk			xkeep = 1;
393135482Sphk			break;
394135482Sphk		case 'Z':
395135482Sphk			parsefmt(Zfmt, 0);
396135482Sphk			Zfmt[0] = '\0';
397113094Sphk			break;
398113094Sphk		case '?':
399113094Sphk		default:
400113094Sphk			usage();
401113094Sphk		}
402113094Sphk	argc -= optind;
403113094Sphk	argv += optind;
404113094Sphk
405113094Sphk	/*
406113094Sphk	 * If there arguments after processing all the options, attempt
407113094Sphk	 * to treat them as a list of process ids.
408113094Sphk	 */
409113094Sphk	while (*argv) {
410113094Sphk		if (!isdigitch(**argv))
411113094Sphk			break;
412113094Sphk		add_list(&pidlist, *argv);
413113094Sphk		argv++;
414113094Sphk	}
415113094Sphk	if (*argv) {
416113094Sphk		fprintf(stderr, "%s: illegal argument: %s\n",
417113094Sphk		    getprogname(), *argv);
418113094Sphk		usage();
419113094Sphk	}
420113094Sphk	if (optfatal)
421135482Sphk		exit(1);		/* Error messages already printed. */
422113270Sphk	if (xkeep < 0)			/* Neither -X nor -x was specified. */
423		xkeep = xkeep_implied;
424
425
426	/*
427	 * Discard setgid privileges if not the running kernel so that bad
428	 * guys can't print interesting stuff from kernel memory.
429	 */
430	if (dropgid) {
431		setgid(getgid());
432		setuid(getuid());
433	}
434
435	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
436	if (kd == 0)
437		errx(1, "%s", errbuf);
438
439	if (!_fmt)
440		parsefmt(dfmt, 0);
441
442	if (nselectors == 0) {
443		uidlist.l.ptr = malloc(sizeof(uid_t));
444		if (uidlist.l.ptr == NULL)
445			errx(1, "malloc failed");
446		nselectors = 1;
447		uidlist.count = uidlist.maxcount = 1;
448		*uidlist.l.uids = getuid();
449	}
450
451	/*
452	 * scan requested variables, noting what structures are needed,
453	 * and adjusting header widths as appropriate.
454	 */
455	scanvars();
456
457	/*
458	 * Get process list.  If the user requested just one selector-
459	 * option, then kvm_getprocs can be asked to return just those
460	 * processes.  Otherwise, have it return all processes, and
461	 * then this routine will search that full list and select the
462	 * processes which match any of the user's selector-options.
463	 */
464	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
465	flag = 0;
466	if (nselectors == 1) {
467		if (gidlist.count == 1) {
468			what = KERN_PROC_RGID | showthreads;
469			flag = *gidlist.l.gids;
470			nselectors = 0;
471		} else if (pgrplist.count == 1) {
472			what = KERN_PROC_PGRP | showthreads;
473			flag = *pgrplist.l.pids;
474			nselectors = 0;
475		} else if (pidlist.count == 1) {
476			what = KERN_PROC_PID | showthreads;
477			flag = *pidlist.l.pids;
478			nselectors = 0;
479		} else if (ruidlist.count == 1) {
480			what = KERN_PROC_RUID | showthreads;
481			flag = *ruidlist.l.uids;
482			nselectors = 0;
483		} else if (sesslist.count == 1) {
484			what = KERN_PROC_SESSION | showthreads;
485			flag = *sesslist.l.pids;
486			nselectors = 0;
487		} else if (ttylist.count == 1) {
488			what = KERN_PROC_TTY | showthreads;
489			flag = *ttylist.l.ttys;
490			nselectors = 0;
491		} else if (uidlist.count == 1) {
492			what = KERN_PROC_UID | showthreads;
493			flag = *uidlist.l.uids;
494			nselectors = 0;
495		} else if (all) {
496			/* No need for this routine to select processes. */
497			nselectors = 0;
498		}
499	}
500
501	/*
502	 * select procs
503	 */
504	nentries = -1;
505	kp = kvm_getprocs(kd, what, flag, &nentries);
506	if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
507		errx(1, "%s", kvm_geterr(kd));
508	nkept = 0;
509	if (nentries > 0) {
510		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
511			errx(1, "malloc failed");
512		for (i = nentries; --i >= 0; ++kp) {
513			/*
514			 * If the user specified multiple selection-criteria,
515			 * then keep any process matched by the inclusive OR
516			 * of all the selection-criteria given.
517			 */
518			if (pidlist.count > 0) {
519				for (elem = 0; elem < pidlist.count; elem++)
520					if (kp->ki_pid == pidlist.l.pids[elem])
521						goto keepit;
522			}
523			/*
524			 * Note that we had to process pidlist before
525			 * filtering out processes which do not have
526			 * a controlling terminal.
527			 */
528			if (xkeep == 0) {
529				if ((kp->ki_tdev == NODEV ||
530				    (kp->ki_flag & P_CONTROLT) == 0))
531					continue;
532			}
533			if (nselectors == 0)
534				goto keepit;
535			if (gidlist.count > 0) {
536				for (elem = 0; elem < gidlist.count; elem++)
537					if (kp->ki_rgid == gidlist.l.gids[elem])
538						goto keepit;
539			}
540			if (pgrplist.count > 0) {
541				for (elem = 0; elem < pgrplist.count; elem++)
542					if (kp->ki_pgid ==
543					    pgrplist.l.pids[elem])
544						goto keepit;
545			}
546			if (ruidlist.count > 0) {
547				for (elem = 0; elem < ruidlist.count; elem++)
548					if (kp->ki_ruid ==
549					    ruidlist.l.uids[elem])
550						goto keepit;
551			}
552			if (sesslist.count > 0) {
553				for (elem = 0; elem < sesslist.count; elem++)
554					if (kp->ki_sid == sesslist.l.pids[elem])
555						goto keepit;
556			}
557			if (ttylist.count > 0) {
558				for (elem = 0; elem < ttylist.count; elem++)
559					if (kp->ki_tdev == ttylist.l.ttys[elem])
560						goto keepit;
561			}
562			if (uidlist.count > 0) {
563				for (elem = 0; elem < uidlist.count; elem++)
564					if (kp->ki_uid == uidlist.l.uids[elem])
565						goto keepit;
566			}
567			/*
568			 * This process did not match any of the user's
569			 * selector-options, so skip the process.
570			 */
571			continue;
572
573		keepit:
574			kinfo[nkept].ki_p = kp;
575			if (needuser)
576				saveuser(&kinfo[nkept]);
577			dynsizevars(&kinfo[nkept]);
578			nkept++;
579		}
580	}
581
582	sizevars();
583
584	/*
585	 * print header
586	 */
587	printheader();
588	if (nkept == 0)
589		exit(1);
590
591	/*
592	 * sort proc list
593	 */
594	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
595	/*
596	 * For each process, call each variable output function.
597	 */
598	for (i = lineno = 0; i < nkept; i++) {
599		for (vent = vhead; vent; vent = vent->next) {
600			(vent->var->oproc)(&kinfo[i], vent);
601			if (vent->next != NULL)
602				(void)putchar(' ');
603		}
604		(void)putchar('\n');
605		if (prtheader && lineno++ == prtheader - 4) {
606			(void)putchar('\n');
607			printheader();
608			lineno = 0;
609		}
610	}
611	free_list(&gidlist);
612	free_list(&pidlist);
613	free_list(&pgrplist);
614	free_list(&ruidlist);
615	free_list(&sesslist);
616	free_list(&ttylist);
617	free_list(&uidlist);
618
619	exit(eval);
620}
621
622static int
623addelem_gid(struct listinfo *inf, const char *elem)
624{
625	struct group *grp;
626	const char *nameorID;
627	char *endp;
628	u_long bigtemp;
629
630	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
631		if (*elem == '\0')
632			warnx("Invalid (zero-length) %s name", inf->lname);
633		else
634			warnx("%s name too long: %s", inf->lname, elem);
635		optfatal = 1;
636		return (0);		/* Do not add this value. */
637	}
638
639	/*
640	 * SUSv3 states that `ps -G grouplist' should match "real-group
641	 * ID numbers", and does not mention group-names.  I do want to
642	 * also support group-names, so this tries for a group-id first,
643	 * and only tries for a name if that doesn't work.  This is the
644	 * opposite order of what is done in addelem_uid(), but in
645	 * practice the order would only matter for group-names which
646	 * are all-numeric.
647	 */
648	grp = NULL;
649	nameorID = "named";
650	errno = 0;
651	bigtemp = strtoul(elem, &endp, 10);
652	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
653		nameorID = "name or ID matches";
654		grp = getgrgid((gid_t)bigtemp);
655	}
656	if (grp == NULL)
657		grp = getgrnam(elem);
658	if (grp == NULL) {
659		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
660		optfatal = 1;
661		return (0);		/* Do not add this value. */
662	}
663
664	if (inf->count >= inf->maxcount)
665		expand_list(inf);
666	inf->l.gids[(inf->count)++] = grp->gr_gid;
667	return (1);
668}
669
670#define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h. */
671static int
672addelem_pid(struct listinfo *inf, const char *elem)
673{
674	char *endp;
675	long tempid;
676
677	if (*elem == '\0')
678		tempid = 0L;
679	else {
680		errno = 0;
681		tempid = strtol(elem, &endp, 10);
682		if (*endp != '\0' || tempid < 0 || elem == endp) {
683			warnx("Invalid %s: %s", inf->lname, elem);
684			errno = ERANGE;
685		} else if (errno != 0 || tempid > BSD_PID_MAX) {
686			warnx("%s too large: %s", inf->lname, elem);
687			errno = ERANGE;
688		}
689		if (errno == ERANGE) {
690			optfatal = 1;
691			return (0);	/* Do not add this value. */
692		}
693	}
694
695	if (inf->count >= inf->maxcount)
696		expand_list(inf);
697	inf->l.pids[(inf->count)++] = tempid;
698	return (1);
699}
700#undef	BSD_PID_MAX
701
702static int
703addelem_tty(struct listinfo *inf, const char *elem)
704{
705	const char *ttypath;
706	struct stat sb;
707	char pathbuf[PATH_MAX];
708
709	if (strcmp(elem, "co") == 0)
710		ttypath = strdup(_PATH_CONSOLE);
711	else if (*elem == '/')
712		ttypath = elem;
713	else {
714		strlcpy(pathbuf, _PATH_TTY, sizeof(pathbuf));
715		strlcat(pathbuf, elem, sizeof(pathbuf));
716		ttypath = pathbuf;
717	}
718
719	if (stat(ttypath, &sb) == -1) {
720		warn("%s", ttypath);
721		optfatal = 1;
722		return (0);		/* Do not add this value. */
723	}
724	if (!S_ISCHR(sb.st_mode)) {
725		warn("%s: Not a terminal", ttypath);
726		optfatal = 1;
727		return (0);		/* Do not add this value. */
728	}
729
730	if (inf->count >= inf->maxcount)
731		expand_list(inf);
732	inf->l.ttys[(inf->count)++] = sb.st_rdev;
733	return (1);
734}
735
736static int
737addelem_uid(struct listinfo *inf, const char *elem)
738{
739	struct passwd *pwd;
740	char *endp;
741	u_long bigtemp;
742
743	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
744		if (*elem == '\0')
745			warnx("Invalid (zero-length) %s name", inf->lname);
746		else
747			warnx("%s name too long: %s", inf->lname, elem);
748		optfatal = 1;
749		return (0);		/* Do not add this value. */
750	}
751
752	pwd = getpwnam(elem);
753	if (pwd == NULL) {
754		errno = 0;
755		bigtemp = strtoul(elem, &endp, 10);
756		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
757			warnx("No %s named '%s'", inf->lname, elem);
758		else {
759			/* The string is all digits, so it might be a userID. */
760			pwd = getpwuid((uid_t)bigtemp);
761			if (pwd == NULL)
762				warnx("No %s name or ID matches '%s'",
763				    inf->lname, elem);
764		}
765	}
766	if (pwd == NULL) {
767		/*
768		 * These used to be treated as minor warnings (and the
769		 * option was simply ignored), but now they are fatal
770		 * errors (and the command will be aborted).
771		 */
772		optfatal = 1;
773		return (0);		/* Do not add this value. */
774	}
775
776	if (inf->count >= inf->maxcount)
777		expand_list(inf);
778	inf->l.uids[(inf->count)++] = pwd->pw_uid;
779	return (1);
780}
781
782static void
783add_list(struct listinfo *inf, const char *argp)
784{
785	const char *savep;
786	char *cp, *endp;
787	int toolong;
788	char elemcopy[PATH_MAX];
789
790	while (*argp != '\0') {
791		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
792			argp++;
793		savep = argp;
794		toolong = 0;
795		cp = elemcopy;
796		if (strchr(T_SEP, *argp) == NULL) {
797			endp = elemcopy + sizeof(elemcopy) - 1;
798			while (*argp != '\0' && cp <= endp &&
799			    strchr(W_SEP T_SEP, *argp) == NULL)
800				*cp++ = *argp++;
801			if (cp > endp)
802				toolong = 1;
803		}
804		if (!toolong) {
805			*cp = '\0';
806#ifndef ADD_PS_LISTRESET
807			/*
808			 * This is how the standard expects lists to
809			 * be handled.
810			 */
811			inf->addelem(inf, elemcopy);
812#else
813			/*-
814			 * This would add a simple non-standard-but-convienent
815			 * feature.
816			 *
817			 * XXX - The first time I tried to add this check,
818			 *	it increased the total size of `ps' by 3940
819			 *	bytes on i386!  That's 12% of the entire
820			 *	program!  The `ps.o' file grew by only about
821			 *	40 bytes, but the final (stripped) executable
822			 *	in /bin/ps grew by 12%.  I have not had time
823			 *	to investigate, so skip the feature for now.
824			 */
825			/*
826			 * We now have a single element.  Add it to the
827			 * list, unless the element is ":".  In that case,
828			 * reset the list so previous entries are ignored.
829			 */
830			if (strcmp(elemcopy, ":") == 0)
831				inf->count = 0;
832			else
833				inf->addelem(inf, elemcopy);
834#endif
835		} else {
836			/*
837			 * The string is too long to copy.  Find the end
838			 * of the string to print out the warning message.
839			 */
840			while (*argp != '\0' && strchr(W_SEP T_SEP,
841			    *argp) == NULL)
842				argp++;
843			warnx("Value too long: %.*s", (int)(argp - savep),
844			    savep);
845			optfatal = 1;
846		}
847		/*
848		 * Skip over any number of trailing whitespace characters,
849		 * but only one (at most) trailing element-terminating
850		 * character.
851		 */
852		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
853			argp++;
854		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
855			argp++;
856			/* Catch case where string ended with a comma. */
857			if (*argp == '\0')
858				inf->addelem(inf, argp);
859		}
860	}
861}
862
863static void *
864expand_list(struct listinfo *inf)
865{
866	void *newlist;
867	int newmax;
868
869	newmax = (inf->maxcount + 1) << 1;
870	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
871	if (newlist == NULL) {
872		free(inf->l.ptr);
873		errx(1, "realloc to %d %ss failed", newmax,
874		    inf->lname);
875	}
876	inf->maxcount = newmax;
877	inf->l.ptr = newlist;
878
879	return (newlist);
880}
881
882static void
883free_list(struct listinfo *inf)
884{
885
886	inf->count = inf->elemsize = inf->maxcount = 0;
887	if (inf->l.ptr != NULL)
888		free(inf->l.ptr);
889	inf->addelem = NULL;
890	inf->lname = NULL;
891	inf->l.ptr = NULL;
892}
893
894static void
895init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
896    const char *lname)
897{
898
899	inf->count = inf->maxcount = 0;
900	inf->elemsize = elemsize;
901	inf->addelem = artn;
902	inf->lname = lname;
903	inf->l.ptr = NULL;
904}
905
906VARENT *
907find_varentry(VAR *v)
908{
909	struct varent *vent;
910
911	for (vent = vhead; vent; vent = vent->next) {
912		if (strcmp(vent->var->name, v->name) == 0)
913			return vent;
914	}
915	return NULL;
916}
917
918static void
919scanvars(void)
920{
921	struct varent *vent;
922	VAR *v;
923
924	for (vent = vhead; vent; vent = vent->next) {
925		v = vent->var;
926		if (v->flag & DSIZ) {
927			v->dwidth = v->width;
928			v->width = 0;
929		}
930		if (v->flag & USER)
931			needuser = 1;
932		if (v->flag & COMM)
933			needcomm = 1;
934	}
935}
936
937static void
938dynsizevars(KINFO *ki)
939{
940	struct varent *vent;
941	VAR *v;
942	int i;
943
944	for (vent = vhead; vent; vent = vent->next) {
945		v = vent->var;
946		if (!(v->flag & DSIZ))
947			continue;
948		i = (v->sproc)( ki);
949		if (v->width < i)
950			v->width = i;
951		if (v->width > v->dwidth)
952			v->width = v->dwidth;
953	}
954}
955
956static void
957sizevars(void)
958{
959	struct varent *vent;
960	VAR *v;
961	int i;
962
963	for (vent = vhead; vent; vent = vent->next) {
964		v = vent->var;
965		i = strlen(vent->header);
966		if (v->width < i)
967			v->width = i;
968		totwidth += v->width + 1;	/* +1 for space */
969	}
970	totwidth--;
971}
972
973static const char *
974fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
975    char *comm, int maxlen)
976{
977	const char *s;
978
979	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
980	return (s);
981}
982
983#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
984
985static void
986saveuser(KINFO *ki)
987{
988
989	if (ki->ki_p->ki_sflag & PS_INMEM) {
990		/*
991		 * The u-area might be swapped out, and we can't get
992		 * at it because we have a crashdump and no swap.
993		 * If it's here fill in these fields, otherwise, just
994		 * leave them 0.
995		 */
996		ki->ki_valid = 1;
997	} else
998		ki->ki_valid = 0;
999	/*
1000	 * save arguments if needed
1001	 */
1002	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
1003		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
1004		    MAXCOMLEN));
1005	} else if (needcomm) {
1006		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
1007	} else {
1008		ki->ki_args = NULL;
1009	}
1010	if (needenv && UREADOK(ki)) {
1011		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
1012	} else if (needenv) {
1013		ki->ki_env = malloc(3);
1014		strcpy(ki->ki_env, "()");
1015	} else {
1016		ki->ki_env = NULL;
1017	}
1018}
1019
1020static int
1021pscomp(const void *a, const void *b)
1022{
1023	const KINFO *ka, *kb;
1024	double cpua, cpub;
1025	segsz_t sizea, sizeb;
1026
1027	ka = a;
1028	kb = b;
1029	/* SORTCPU and SORTMEM are sorted in descending order. */
1030	if (sortby == SORTCPU) {
1031		cpua = getpcpu(ka);
1032		cpub = getpcpu(kb);
1033		if (cpua < cpub)
1034			return (1);
1035		if (cpua > cpub)
1036			return (-1);
1037	}
1038	if (sortby == SORTMEM) {
1039		sizea = ka->ki_p->ki_tsize + ka->ki_p->ki_dsize +
1040		    ka->ki_p->ki_ssize;
1041		sizeb = kb->ki_p->ki_tsize + kb->ki_p->ki_dsize +
1042		    kb->ki_p->ki_ssize;
1043		if (sizea < sizeb)
1044			return (1);
1045		if (sizea > sizeb)
1046			return (-1);
1047	}
1048	/*
1049	 * TTY's are sorted in ascending order, except that all NODEV
1050	 * processes come before all processes with a device.
1051	 */
1052	if (ka->ki_p->ki_tdev == NODEV && kb->ki_p->ki_tdev != NODEV)
1053		return (-1);
1054	if (ka->ki_p->ki_tdev != NODEV && kb->ki_p->ki_tdev == NODEV)
1055		return (1);
1056	if (ka->ki_p->ki_tdev < kb->ki_p->ki_tdev)
1057		return (-1);
1058	if (ka->ki_p->ki_tdev > kb->ki_p->ki_tdev)
1059		return (1);
1060	/* PID's are sorted in ascending order. */
1061	if (ka->ki_p->ki_pid < kb->ki_p->ki_pid)
1062		return (-1);
1063	if (ka->ki_p->ki_pid > kb->ki_p->ki_pid)
1064		return (1);
1065	return (0);
1066}
1067
1068/*
1069 * ICK (all for getopt), would rather hide the ugliness
1070 * here than taint the main code.
1071 *
1072 *  ps foo -> ps -foo
1073 *  ps 34 -> ps -p34
1074 *
1075 * The old convention that 't' with no trailing tty arg means the users
1076 * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1077 * feature is available with the option 'T', which takes no argument.
1078 */
1079static char *
1080kludge_oldps_options(const char *optlist, char *origval)
1081{
1082	size_t len;
1083	char *argp, *cp, *newopts, *ns, *optp, *pidp;
1084
1085	/*
1086	 * See if the original value includes any option which takes an
1087	 * argument (and will thus use up the remainder of the string).
1088	 */
1089	argp = NULL;
1090	if (optlist != NULL) {
1091		for (cp = origval; *cp != '\0'; cp++) {
1092			optp = strchr(optlist, *cp);
1093			if ((optp != NULL) && *(optp + 1) == ':') {
1094				argp = cp;
1095				break;
1096			}
1097		}
1098	}
1099	if (argp != NULL && *origval == '-')
1100		return (origval);
1101
1102	/*
1103	 * if last letter is a 't' flag with no argument (in the context
1104	 * of the oldps options -- option string NOT starting with a '-' --
1105	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1106	 *
1107	 * However, if a flag accepting a string argument is found earlier
1108	 * in the option string (including a possible `t' flag), then the
1109	 * remainder of the string must be the argument to that flag; so
1110	 * do not modify that argument.  Note that a trailing `t' would
1111	 * cause argp to be set, if argp was not already set by some
1112	 * earlier option.
1113	 */
1114	len = strlen(origval);
1115	cp = origval + len - 1;
1116	pidp = NULL;
1117	if (*cp == 't' && *origval != '-' && cp == argp)
1118		*cp = 'T';
1119	else if (argp == NULL) {
1120		/*
1121		 * The original value did not include any option which takes
1122		 * an argument (and that would include `p' and `t'), so check
1123		 * the value for trailing number, or comma-separated list of
1124		 * numbers, which we will treat as a pid request.
1125		 */
1126		if (isdigitch(*cp)) {
1127			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1128				--cp;
1129			pidp = cp + 1;
1130		}
1131	}
1132
1133	/*
1134	 * If nothing needs to be added to the string, then return
1135	 * the "original" (although possibly modified) value.
1136	 */
1137	if (*origval == '-' && pidp == NULL)
1138		return (origval);
1139
1140	/*
1141	 * Create a copy of the string to add '-' and/or 'p' to the
1142	 * original value.
1143	 */
1144	if ((newopts = ns = malloc(len + 3)) == NULL)
1145		errx(1, "malloc failed");
1146
1147	if (*origval != '-')
1148		*ns++ = '-';	/* add option flag */
1149
1150	if (pidp == NULL)
1151		strcpy(ns, origval);
1152	else {
1153		/*
1154		 * Copy everything before the pid string, add the `p',
1155		 * and then copy the pid string.
1156		 */
1157		len = pidp - origval;
1158		memcpy(ns, origval, len);
1159		ns += len;
1160		*ns++ = 'p';
1161		strcpy(ns, pidp);
1162	}
1163
1164	return (newopts);
1165}
1166
1167static void
1168usage(void)
1169{
1170#define	SINGLE_OPTS	"[-aC" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1171
1172	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1173	    "usage: ps " SINGLE_OPTS " [-G gid[,gid]] [-O|o fmt]",
1174	    "          [-p pid[,pid]] [-t tty[,tty]] [-U user[,user]]",
1175	    "          [-M core] [-N system]",
1176	    "       ps [-L]");
1177	exit(1);
1178}
1179