ps.c revision 129971
193383Smdodd/*-
293383Smdodd * Copyright (c) 1990, 1993, 1994
321826Sjoerg *	The Regents of the University of California.  All rights reserved.
421826Sjoerg *
521826Sjoerg * Redistribution and use in source and binary forms, with or without
621826Sjoerg * modification, are permitted provided that the following conditions
721826Sjoerg * are met:
821826Sjoerg * 1. Redistributions of source code must retain the above copyright
921826Sjoerg *    notice, this list of conditions and the following disclaimer.
1021826Sjoerg * 2. Redistributions in binary form must reproduce the above copyright
1121826Sjoerg *    notice, this list of conditions and the following disclaimer in the
1221826Sjoerg *    documentation and/or other materials provided with the distribution.
1393383Smdodd * 4. Neither the name of the University nor the names of its contributors
1421826Sjoerg *    may be used to endorse or promote products derived from this software
1521826Sjoerg *    without specific prior written permission.
1621826Sjoerg *
1721826Sjoerg * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1821826Sjoerg * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1921826Sjoerg * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2021826Sjoerg * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2121826Sjoerg * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2221826Sjoerg * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2321826Sjoerg * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2421826Sjoerg * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2521826Sjoerg * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2693383Smdodd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2721826Sjoerg * SUCH DAMAGE.
2821826Sjoerg * ------+---------+---------+-------- + --------+---------+---------+---------*
2921826Sjoerg * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
30119418Sobrien * All rights reserved.
31119418Sobrien *
32119418Sobrien * Significant modifications made to bring `ps' options somewhat closer
3321826Sjoerg * to the standard for `ps' as described in SingleUnixSpec-v3.
3421826Sjoerg * ------+---------+---------+-------- + --------+---------+---------+---------*
3521826Sjoerg */
3693383Smdodd
3721826Sjoerg#ifndef lint
3821826Sjoergstatic const char copyright[] =
3921826Sjoerg"@(#) Copyright (c) 1990, 1993, 1994\n\
4021826Sjoerg	The Regents of the University of California.  All rights reserved.\n";
4121826Sjoerg#endif /* not lint */
4221826Sjoerg
4321826Sjoerg#if 0
4421826Sjoerg#ifndef lint
4593383Smdoddstatic char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
4621826Sjoerg#endif /* not lint */
4721826Sjoerg#endif
4893383Smdodd
4993383Smdodd#include <sys/cdefs.h>
5093383Smdodd__FBSDID("$FreeBSD: head/bin/ps/ps.c 129971 2004-06-01 23:27:11Z gad $");
5193383Smdodd
5221830Sjoerg#include <sys/param.h>
5321826Sjoerg#include <sys/proc.h>
5421826Sjoerg#include <sys/user.h>
5521826Sjoerg#include <sys/stat.h>
5621826Sjoerg#include <sys/ioctl.h>
5721826Sjoerg#include <sys/sysctl.h>
5821826Sjoerg
5921826Sjoerg#include <ctype.h>
6021826Sjoerg#include <err.h>
6121826Sjoerg#include <errno.h>
6221826Sjoerg#include <fcntl.h>
6321826Sjoerg#include <grp.h>
6421826Sjoerg#include <kvm.h>
6521826Sjoerg#include <limits.h>
66298955Spfg#include <locale.h>
6721826Sjoerg#include <paths.h>
6821826Sjoerg#include <pwd.h>
6921826Sjoerg#include <stdio.h>
7021826Sjoerg#include <stdlib.h>
7121826Sjoerg#include <string.h>
7221826Sjoerg#include <unistd.h>
7321826Sjoerg
7421826Sjoerg#include "ps.h"
7521826Sjoerg
7621826Sjoerg#define	W_SEP	" \t"		/* "Whitespace" list separators */
7721826Sjoerg#define	T_SEP	","		/* "Terminate-element" list separators */
7821826Sjoerg
7921826Sjoerg#ifdef LAZY_PS
8021826Sjoerg#define	DEF_UREAD	0
8121826Sjoerg#define	OPT_LAZY_f	"f"
8221826Sjoerg#else
8393383Smdodd#define	DEF_UREAD	1	/* Always do the more-expensive read. */
8421826Sjoerg#define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
8521826Sjoerg#endif
8621826Sjoerg
8721826Sjoerg/*
8821826Sjoerg * isdigit takes an `int', but expects values in the range of unsigned char.
8921826Sjoerg * This wrapper ensures that values from a 'char' end up in the correct range.
9021826Sjoerg */
9121826Sjoerg#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
9221826Sjoerg
9321826Sjoergint	 cflag;			/* -c */
9421826Sjoergint	 eval;			/* Exit value */
9521826Sjoergtime_t	 now;			/* Current time(3) value */
9621826Sjoergint	 rawcpu;		/* -C */
9721826Sjoergint	 sumrusage;		/* -S */
9821826Sjoergint	 termwidth;		/* Width of the screen (0 == infinity). */
9921826Sjoergint	 totwidth;		/* Calculated-width of requested variables. */
10021826Sjoerg
10121826Sjoergstruct varent *vhead;
10221826Sjoerg
10321826Sjoergstatic int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
10421826Sjoergstatic kvm_t	*kd;
10521826Sjoergstatic KINFO	*kinfo;
10621826Sjoergstatic int	 needcomm;	/* -o "command" */
10721826Sjoergstatic int	 needenv;	/* -e */
10821826Sjoergstatic int	 needuser;	/* -o "user" */
10921826Sjoergstatic int	 optfatal;	/* Fatal error parsing some list-option. */
11021826Sjoerg
11121826Sjoergstatic enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
11221826Sjoerg
11321826Sjoergstruct listinfo;
11421826Sjoergtypedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
11521826Sjoerg
11621826Sjoergstruct listinfo {
11721826Sjoerg	int		 count;
11821826Sjoerg	int		 maxcount;
11921826Sjoerg	int		 elemsize;
12021826Sjoerg	addelem_rtn	*addelem;
12121826Sjoerg	const char	*lname;
12221826Sjoerg	union {
12321826Sjoerg		gid_t	*gids;
12421826Sjoerg		pid_t	*pids;
12521826Sjoerg		dev_t	*ttys;
12621826Sjoerg		uid_t	*uids;
12721826Sjoerg		void	*ptr;
12821826Sjoerg	} l;
12921826Sjoerg};
13021826Sjoerg
13121826Sjoergstatic int	 addelem_gid(struct listinfo *, const char *);
13221826Sjoergstatic int	 addelem_pid(struct listinfo *, const char *);
13321826Sjoergstatic int	 addelem_tty(struct listinfo *, const char *);
13421826Sjoergstatic int	 addelem_uid(struct listinfo *, const char *);
13521826Sjoergstatic void	 add_list(struct listinfo *, const char *);
13621826Sjoergstatic void	 dynsizevars(KINFO *);
13721826Sjoergstatic void	*expand_list(struct listinfo *);
13821826Sjoergstatic const char *
13921826Sjoerg		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
14021826Sjoerg		    KINFO *, char *, int);
14121826Sjoergstatic void	 free_list(struct listinfo *);
14221826Sjoergstatic void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
14321826Sjoergstatic char	*kludge_oldps_options(const char *, char *, const char *);
14421826Sjoergstatic int	 pscomp(const void *, const void *);
14521826Sjoergstatic void	 saveuser(KINFO *);
14621826Sjoergstatic void	 scanvars(void);
14721826Sjoergstatic void	 sizevars(void);
14821826Sjoergstatic void	 usage(void);
14921826Sjoerg
15021826Sjoergstatic char dfmt[] = "pid,tt,state,time,command";
15121826Sjoergstatic char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
15221826Sjoergstatic char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
15321826Sjoerg			"tt,time,command";
15421826Sjoergstatic char   o1[] = "pid";
15521826Sjoergstatic char   o2[] = "tt,state,time,command";
15621826Sjoergstatic char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
15721826Sjoergstatic char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
15821826Sjoerg			"%cpu,%mem,command";
15921826Sjoergstatic char Zfmt[] = "label";
16021826Sjoerg
16121826Sjoerg#define	PS_ARGS	"AaCce" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
16221826Sjoerg
16321826Sjoergint
16421826Sjoergmain(int argc, char *argv[])
16521826Sjoerg{
16621826Sjoerg	struct listinfo gidlist, pgrplist, pidlist;
16721826Sjoerg	struct listinfo ruidlist, sesslist, ttylist, uidlist;
16821826Sjoerg	struct kinfo_proc *kp;
16921826Sjoerg	struct varent *vent;
17021826Sjoerg	struct winsize ws;
17121826Sjoerg	const char *nlistf, *memf;
17221826Sjoerg	char *cols;
17321826Sjoerg	int all, ch, dropgid, elem, flag, _fmt, i, lineno;
17421826Sjoerg	int nentries, nkept, nselectors;
17521826Sjoerg	int prtheader, showthreads, wflag, what, xkeep, xkeep_implied;
17621826Sjoerg	char errbuf[_POSIX2_LINE_MAX];
17721826Sjoerg
17821826Sjoerg	(void) setlocale(LC_ALL, "");
17921826Sjoerg	time(&now);			/* Used by routines in print.c. */
18021826Sjoerg
18121826Sjoerg	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
18221826Sjoerg		termwidth = atoi(cols);
18321826Sjoerg	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
18421826Sjoerg	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
18521826Sjoerg	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
18621826Sjoerg	     ws.ws_col == 0)
18721826Sjoerg		termwidth = 79;
18821826Sjoerg	else
18921826Sjoerg		termwidth = ws.ws_col - 1;
19021826Sjoerg
19121826Sjoerg	/*
19221826Sjoerg	 * Hide a number of option-processing kludges in a separate routine,
19321826Sjoerg	 * to support some historical BSD behaviors, such as `ps axu'.
19421826Sjoerg	 */
19521826Sjoerg	if (argc > 1)
19621826Sjoerg		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
19721826Sjoerg
19821826Sjoerg	all = dropgid = _fmt = nselectors = optfatal = 0;
19921826Sjoerg	prtheader = showthreads = wflag = xkeep_implied = 0;
20021826Sjoerg	xkeep = -1;			/* Neither -x nor -X. */
20121826Sjoerg	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
20221826Sjoerg	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
20321826Sjoerg	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
20421826Sjoerg	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
20521826Sjoerg	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
20621826Sjoerg	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
20721826Sjoerg	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
20821826Sjoerg	memf = nlistf = _PATH_DEVNULL;
20921826Sjoerg	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
21021826Sjoerg		switch ((char)ch) {
21121826Sjoerg		case 'A':
21221826Sjoerg			/*
21321826Sjoerg			 * Exactly the same as `-ax'.   This has been
21421826Sjoerg			 * added for compatability with SUSv3, but for
21521826Sjoerg			 * now it will not be described in the man page.
21621826Sjoerg			 */
21721826Sjoerg			nselectors++;
21821826Sjoerg			all = xkeep = 1;
21921826Sjoerg			break;
22093383Smdodd		case 'a':
22193383Smdodd			nselectors++;
22221826Sjoerg			all = 1;
22321826Sjoerg			break;
22421826Sjoerg		case 'C':
22521826Sjoerg			rawcpu = 1;
22621826Sjoerg			break;
22721826Sjoerg		case 'c':
22821826Sjoerg			cflag = 1;
22921826Sjoerg			break;
23021826Sjoerg		case 'e':			/* XXX set ufmt */
23121826Sjoerg			needenv = 1;
23221826Sjoerg			break;
23321826Sjoerg#ifdef LAZY_PS
23421826Sjoerg		case 'f':
23521826Sjoerg			if (getuid() == 0 || getgid() == 0)
23621826Sjoerg				forceuread = 1;
23721826Sjoerg			break;
23821826Sjoerg#endif
23921826Sjoerg		case 'G':
24021826Sjoerg			add_list(&gidlist, optarg);
24121826Sjoerg			xkeep_implied = 1;
24221826Sjoerg			nselectors++;
24321826Sjoerg			break;
24421826Sjoerg		case 'g':
24521826Sjoerg#if 0
24621826Sjoerg			/*-
24721826Sjoerg			 * XXX - This SUSv3 behavior is still under debate
24821826Sjoerg			 *	since it conflicts with the (undocumented)
24921826Sjoerg			 *	`-g' option.  So we skip it for now.
25021826Sjoerg			 */
25121826Sjoerg			add_list(&pgrplist, optarg);
25221826Sjoerg			xkeep_implied = 1;
25321826Sjoerg			nselectors++;
25421826Sjoerg			break;
25521826Sjoerg#else
25621826Sjoerg			/* The historical BSD-ish (from SunOS) behavior. */
25721826Sjoerg			break;			/* no-op */
25821826Sjoerg#endif
25921826Sjoerg		case 'H':
26021826Sjoerg			showthreads = KERN_PROC_INC_THREAD;
26121826Sjoerg			break;
26221826Sjoerg		case 'h':
26321826Sjoerg			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
26421826Sjoerg			break;
26593383Smdodd		case 'j':
26621826Sjoerg			parsefmt(jfmt, 0);
26721826Sjoerg			_fmt = 1;
26821826Sjoerg			jfmt[0] = '\0';
26921826Sjoerg			break;
27021826Sjoerg		case 'L':
27121826Sjoerg			showkey();
27221826Sjoerg			exit(0);
27393383Smdodd		case 'l':
27421826Sjoerg			parsefmt(lfmt, 0);
27521826Sjoerg			_fmt = 1;
27621826Sjoerg			lfmt[0] = '\0';
27721826Sjoerg			break;
27821826Sjoerg		case 'M':
27921826Sjoerg			memf = optarg;
28021826Sjoerg			dropgid = 1;
28121826Sjoerg			break;
28221826Sjoerg		case 'm':
28321826Sjoerg			sortby = SORTMEM;
28421826Sjoerg			break;
28521826Sjoerg		case 'N':
28621826Sjoerg			nlistf = optarg;
28721826Sjoerg			dropgid = 1;
28821826Sjoerg			break;
28921826Sjoerg		case 'O':
29021826Sjoerg			parsefmt(o1, 1);
29121826Sjoerg			parsefmt(optarg, 1);
29221826Sjoerg			parsefmt(o2, 1);
29321826Sjoerg			o1[0] = o2[0] = '\0';
29421826Sjoerg			_fmt = 1;
29521826Sjoerg			break;
29621826Sjoerg		case 'o':
29721826Sjoerg			parsefmt(optarg, 1);
29821826Sjoerg			_fmt = 1;
29921826Sjoerg			break;
30021826Sjoerg		case 'p':
30121826Sjoerg			add_list(&pidlist, optarg);
30221826Sjoerg			/*
30321826Sjoerg			 * Note: `-p' does not *set* xkeep, but any values
30421826Sjoerg			 * from pidlist are checked before xkeep is.  That
30521826Sjoerg			 * way they are always matched, even if the user
30621826Sjoerg			 * specifies `-X'.
30721826Sjoerg			 */
30821826Sjoerg			nselectors++;
30921826Sjoerg			break;
31021826Sjoerg#if 0
31121826Sjoerg		case 'R':
31221826Sjoerg			/*-
31321826Sjoerg			 * XXX - This un-standard option is still under
31421826Sjoerg			 *	debate.  This is what SUSv3 defines as
31521826Sjoerg			 *	the `-U' option, and while it would be
31621826Sjoerg			 *	nice to have, it could cause even more
31721826Sjoerg			 *	confusion to implement it as `-R'.
31821826Sjoerg			 */
31921826Sjoerg			add_list(&ruidlist, optarg);
32021826Sjoerg			xkeep_implied = 1;
32121826Sjoerg			nselectors++;
32221826Sjoerg			break;
32321826Sjoerg#endif
32421826Sjoerg		case 'r':
32521826Sjoerg			sortby = SORTCPU;
32621826Sjoerg			break;
32721826Sjoerg		case 'S':
32821826Sjoerg			sumrusage = 1;
32921826Sjoerg			break;
33021826Sjoerg#if 0
33121826Sjoerg		case 's':
33221826Sjoerg			/*-
33321826Sjoerg			 * XXX - This non-standard option is still under
33421826Sjoerg			 *	debate.  This *is* supported on Solaris,
33521826Sjoerg			 *	Linux, and IRIX, but conflicts with `-s'
33621826Sjoerg			 *	on NetBSD and maybe some older BSD's.
33721826Sjoerg			 */
33821826Sjoerg			add_list(&sesslist, optarg);
33921826Sjoerg			xkeep_implied = 1;
34021826Sjoerg			nselectors++;
34121826Sjoerg			break;
34221826Sjoerg#endif
34321826Sjoerg		case 'T':
34421826Sjoerg			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
34521826Sjoerg				errx(1, "stdin: not a terminal");
34621826Sjoerg			/* FALLTHROUGH */
34721826Sjoerg		case 't':
34821826Sjoerg			add_list(&ttylist, optarg);
34921826Sjoerg			xkeep_implied = 1;
35021826Sjoerg			nselectors++;
35121826Sjoerg			break;
35221826Sjoerg		case 'U':
35321826Sjoerg			/* This is what SUSv3 defines as the `-u' option. */
35421826Sjoerg			add_list(&uidlist, optarg);
35521826Sjoerg			xkeep_implied = 1;
35621826Sjoerg			nselectors++;
35721826Sjoerg			break;
35821826Sjoerg		case 'u':
35921826Sjoerg			parsefmt(ufmt, 0);
36021826Sjoerg			sortby = SORTCPU;
36121826Sjoerg			_fmt = 1;
36221826Sjoerg			ufmt[0] = '\0';
36321826Sjoerg			break;
36421826Sjoerg		case 'v':
36521826Sjoerg			parsefmt(vfmt, 0);
36621826Sjoerg			sortby = SORTMEM;
36721826Sjoerg			_fmt = 1;
36821826Sjoerg			vfmt[0] = '\0';
36921826Sjoerg			break;
37021826Sjoerg		case 'w':
37121826Sjoerg			if (wflag)
37221826Sjoerg				termwidth = UNLIMITED;
37321826Sjoerg			else if (termwidth < 131)
37421826Sjoerg				termwidth = 131;
37521826Sjoerg			wflag++;
37621826Sjoerg			break;
37721826Sjoerg		case 'X':
37821826Sjoerg			/*
37921826Sjoerg			 * Note that `-X' and `-x' are not standard "selector"
38021826Sjoerg			 * options. For most selector-options, we check *all*
38121826Sjoerg			 * processes to see if any are matched by the given
38221826Sjoerg			 * value(s).  After we have a set of all the matched
38321826Sjoerg			 * processes, then `-X' and `-x' govern whether we
38421826Sjoerg			 * modify that *matched* set for processes which do
38521826Sjoerg			 * not have a controlling terminal.  `-X' causes
38621826Sjoerg			 * those processes to be deleted from the matched
38721826Sjoerg			 * set, while `-x' causes them to be kept.
38821826Sjoerg			 */
38921826Sjoerg			xkeep = 0;
39021826Sjoerg			break;
39121826Sjoerg		case 'x':
39221826Sjoerg			xkeep = 1;
39321826Sjoerg			break;
39421826Sjoerg		case 'Z':
39521826Sjoerg			parsefmt(Zfmt, 0);
39621826Sjoerg			Zfmt[0] = '\0';
39721826Sjoerg			break;
39821826Sjoerg		case '?':
39921826Sjoerg		default:
40021826Sjoerg			usage();
40121826Sjoerg		}
40221826Sjoerg	argc -= optind;
40321826Sjoerg	argv += optind;
40421826Sjoerg
40521826Sjoerg	/*
40621826Sjoerg	 * If there arguments after processing all the options, attempt
40721826Sjoerg	 * to treat them as a list of process ids.
40821826Sjoerg	 */
40921826Sjoerg	while (*argv) {
41021826Sjoerg		if (!isdigitch(**argv))
41121826Sjoerg			break;
41221826Sjoerg		add_list(&pidlist, *argv);
41321826Sjoerg		argv++;
41421826Sjoerg	}
41521826Sjoerg	if (*argv) {
41621826Sjoerg		fprintf(stderr, "%s: illegal argument: %s\n",
41721826Sjoerg		    getprogname(), *argv);
41821826Sjoerg		usage();
41921826Sjoerg	}
42021826Sjoerg	if (optfatal)
42121826Sjoerg		exit(1);		/* Error messages already printed. */
42221826Sjoerg	if (xkeep < 0)			/* Neither -X nor -x was specified. */
42321826Sjoerg		xkeep = xkeep_implied;
42421826Sjoerg
42521826Sjoerg
42621826Sjoerg	/*
42721826Sjoerg	 * Discard setgid privileges if not the running kernel so that bad
42821826Sjoerg	 * guys can't print interesting stuff from kernel memory.
42921826Sjoerg	 */
43021826Sjoerg	if (dropgid)
43121826Sjoerg		setgid(getgid());
43221826Sjoerg
43321826Sjoerg	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
43421826Sjoerg	if (kd == 0)
43521826Sjoerg		errx(1, "%s", errbuf);
43621826Sjoerg
43721826Sjoerg	if (!_fmt)
43821826Sjoerg		parsefmt(dfmt, 0);
43921826Sjoerg
44021826Sjoerg	if (nselectors == 0) {
44121826Sjoerg		uidlist.l.ptr = malloc(sizeof(uid_t));
44221826Sjoerg		if (uidlist.l.ptr == NULL)
44321826Sjoerg			errx(1, "malloc failed");
44421826Sjoerg		nselectors = 1;
44521826Sjoerg		uidlist.count = uidlist.maxcount = 1;
44621826Sjoerg		*uidlist.l.uids = getuid();
44793383Smdodd	}
44821826Sjoerg
44921826Sjoerg	/*
45021826Sjoerg	 * scan requested variables, noting what structures are needed,
45121826Sjoerg	 * and adjusting header widths as appropriate.
45221826Sjoerg	 */
45321826Sjoerg	scanvars();
45421826Sjoerg
45521826Sjoerg	/*
45621826Sjoerg	 * Get process list.  If the user requested just one selector-
45793383Smdodd	 * option, then kvm_getprocs can be asked to return just those
45821826Sjoerg	 * processes.  Otherwise, have it return all processes, and
45921826Sjoerg	 * then this routine will search that full list and select the
46021826Sjoerg	 * processes which match any of the user's selector-options.
46121826Sjoerg	 */
46221826Sjoerg	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
46321826Sjoerg	flag = 0;
46421826Sjoerg	if (nselectors == 1) {
46521826Sjoerg		if (gidlist.count == 1) {
46621826Sjoerg			what = KERN_PROC_RGID | showthreads;
46721826Sjoerg			flag = *gidlist.l.gids;
46821826Sjoerg			nselectors = 0;
46921826Sjoerg		} else if (pgrplist.count == 1) {
47021826Sjoerg			what = KERN_PROC_PGRP | showthreads;
47121826Sjoerg			flag = *pgrplist.l.pids;
47221826Sjoerg			nselectors = 0;
47321826Sjoerg		} else if (pidlist.count == 1) {
47421826Sjoerg			what = KERN_PROC_PID | showthreads;
47521826Sjoerg			flag = *pidlist.l.pids;
47621826Sjoerg			nselectors = 0;
47721826Sjoerg		} else if (ruidlist.count == 1) {
47821826Sjoerg			what = KERN_PROC_RUID | showthreads;
47921826Sjoerg			flag = *ruidlist.l.uids;
48021826Sjoerg			nselectors = 0;
48121826Sjoerg		} else if (sesslist.count == 1) {
48221826Sjoerg			what = KERN_PROC_SESSION | showthreads;
48321826Sjoerg			flag = *sesslist.l.pids;
48421826Sjoerg			nselectors = 0;
48521826Sjoerg		} else if (ttylist.count == 1) {
48621826Sjoerg			what = KERN_PROC_TTY | showthreads;
48721826Sjoerg			flag = *ttylist.l.ttys;
48821826Sjoerg			nselectors = 0;
48921826Sjoerg		} else if (uidlist.count == 1) {
49021826Sjoerg			what = KERN_PROC_UID | showthreads;
49121826Sjoerg			flag = *uidlist.l.uids;
49293383Smdodd			nselectors = 0;
49321826Sjoerg		} else if (all) {
49421826Sjoerg			/* No need for this routine to select processes. */
49521826Sjoerg			nselectors = 0;
49621826Sjoerg		}
49721826Sjoerg	}
49821826Sjoerg
49993383Smdodd	/*
50093383Smdodd	 * select procs
50193383Smdodd	 */
50293383Smdodd	nentries = -1;
50393383Smdodd	kp = kvm_getprocs(kd, what, flag, &nentries);
50493383Smdodd	if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
50521826Sjoerg		errx(1, "%s", kvm_geterr(kd));
50621826Sjoerg	nkept = 0;
50721826Sjoerg	if (nentries > 0) {
50821826Sjoerg		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
50921826Sjoerg			errx(1, "malloc failed");
51021826Sjoerg		for (i = nentries; --i >= 0; ++kp) {
51121826Sjoerg			/*
51293383Smdodd			 * If the user specified multiple selection-criteria,
51321826Sjoerg			 * then keep any process matched by the inclusive OR
51421826Sjoerg			 * of all the selection-criteria given.
51521826Sjoerg			 */
51621826Sjoerg			if (pidlist.count > 0) {
51721826Sjoerg				for (elem = 0; elem < pidlist.count; elem++)
51821826Sjoerg					if (kp->ki_pid == pidlist.l.pids[elem])
51921826Sjoerg						goto keepit;
52021826Sjoerg			}
52121826Sjoerg			/*
52221826Sjoerg			 * Note that we had to process pidlist before
52321826Sjoerg			 * filtering out processes which do not have
52421826Sjoerg			 * a controlling terminal.
52521826Sjoerg			 */
52621826Sjoerg			if (xkeep == 0) {
52721826Sjoerg				if ((kp->ki_tdev == NODEV ||
52821826Sjoerg				    (kp->ki_flag & P_CONTROLT) == 0))
52921826Sjoerg					continue;
53093383Smdodd			}
53121826Sjoerg			if (nselectors == 0)
53221826Sjoerg				goto keepit;
53321826Sjoerg			if (gidlist.count > 0) {
53421826Sjoerg				for (elem = 0; elem < gidlist.count; elem++)
53521826Sjoerg					if (kp->ki_rgid == gidlist.l.gids[elem])
53621826Sjoerg						goto keepit;
53721826Sjoerg			}
53821826Sjoerg			if (pgrplist.count > 0) {
53921826Sjoerg				for (elem = 0; elem < pgrplist.count; elem++)
54021826Sjoerg					if (kp->ki_pgid ==
54121826Sjoerg					    pgrplist.l.pids[elem])
54293383Smdodd						goto keepit;
54393383Smdodd			}
54493383Smdodd			if (ruidlist.count > 0) {
54593383Smdodd				for (elem = 0; elem < ruidlist.count; elem++)
54693383Smdodd					if (kp->ki_ruid ==
54793383Smdodd					    ruidlist.l.uids[elem])
54893383Smdodd						goto keepit;
54993383Smdodd			}
55093383Smdodd			if (sesslist.count > 0) {
55193383Smdodd				for (elem = 0; elem < sesslist.count; elem++)
55221826Sjoerg					if (kp->ki_sid == sesslist.l.pids[elem])
55321826Sjoerg						goto keepit;
55421826Sjoerg			}
55521826Sjoerg			if (ttylist.count > 0) {
55693383Smdodd				for (elem = 0; elem < ttylist.count; elem++)
55793383Smdodd					if (kp->ki_tdev == ttylist.l.ttys[elem])
55821826Sjoerg						goto keepit;
55993383Smdodd			}
56093383Smdodd			if (uidlist.count > 0) {
56193383Smdodd				for (elem = 0; elem < uidlist.count; elem++)
56293383Smdodd					if (kp->ki_uid == uidlist.l.uids[elem])
56393383Smdodd						goto keepit;
56493383Smdodd			}
56593383Smdodd			/*
56693383Smdodd			 * This process did not match any of the user's
56793383Smdodd			 * selector-options, so skip the process.
56893383Smdodd			 */
56993383Smdodd			continue;
57093383Smdodd
57193383Smdodd		keepit:
57293383Smdodd			kinfo[nkept].ki_p = kp;
57321826Sjoerg			if (needuser)
57421826Sjoerg				saveuser(&kinfo[nkept]);
57521826Sjoerg			dynsizevars(&kinfo[nkept]);
57621826Sjoerg			nkept++;
57721826Sjoerg		}
57821826Sjoerg	}
57921826Sjoerg
58021826Sjoerg	sizevars();
58121826Sjoerg
58221826Sjoerg	/*
58321826Sjoerg	 * print header
58421826Sjoerg	 */
58521826Sjoerg	printheader();
58621826Sjoerg	if (nkept == 0)
58721826Sjoerg		exit(1);
58821826Sjoerg
58921826Sjoerg	/*
59021826Sjoerg	 * sort proc list
59121826Sjoerg	 */
59221826Sjoerg	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
59321826Sjoerg	/*
59421826Sjoerg	 * For each process, call each variable output function.
59521826Sjoerg	 */
59621826Sjoerg	for (i = lineno = 0; i < nkept; i++) {
59721826Sjoerg		for (vent = vhead; vent; vent = vent->next) {
59821826Sjoerg			(vent->var->oproc)(&kinfo[i], vent);
59921826Sjoerg			if (vent->next != NULL)
60021826Sjoerg				(void)putchar(' ');
60121826Sjoerg		}
60221826Sjoerg		(void)putchar('\n');
60321826Sjoerg		if (prtheader && lineno++ == prtheader - 4) {
60421826Sjoerg			(void)putchar('\n');
60593383Smdodd			printheader();
60693383Smdodd			lineno = 0;
60793383Smdodd		}
60821826Sjoerg	}
60993383Smdodd	free_list(&gidlist);
61021826Sjoerg	free_list(&pidlist);
61193383Smdodd	free_list(&pgrplist);
61221826Sjoerg	free_list(&ruidlist);
61321826Sjoerg	free_list(&sesslist);
61421826Sjoerg	free_list(&ttylist);
61521826Sjoerg	free_list(&uidlist);
61693383Smdodd
61793383Smdodd	exit(eval);
61893383Smdodd}
61993383Smdodd
62021826Sjoergstatic int
62121826Sjoergaddelem_gid(struct listinfo *inf, const char *elem)
62221826Sjoerg{
62321826Sjoerg	struct group *grp;
62421826Sjoerg	const char *nameorID;
62521826Sjoerg	char *endp;
62621826Sjoerg	u_long bigtemp;
62721826Sjoerg
62821826Sjoerg	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
62921826Sjoerg		if (*elem == '\0')
63021826Sjoerg			warnx("Invalid (zero-length) %s name", inf->lname);
63121826Sjoerg		else
63221826Sjoerg			warnx("%s name too long: %s", inf->lname, elem);
63321826Sjoerg		optfatal = 1;
63421826Sjoerg		return (0);		/* Do not add this value. */
63521826Sjoerg	}
63621826Sjoerg
63721826Sjoerg	/*
63821826Sjoerg	 * SUSv3 states that `ps -G grouplist' should match "real-group
63921826Sjoerg	 * ID numbers", and does not mention group-names.  I do want to
64021826Sjoerg	 * also support group-names, so this tries for a group-id first,
64121826Sjoerg	 * and only tries for a name if that doesn't work.  This is the
64221826Sjoerg	 * opposite order of what is done in addelem_uid(), but in
64321826Sjoerg	 * practice the order would only matter for group-names which
64421826Sjoerg	 * are all-numeric.
64521826Sjoerg	 */
64621826Sjoerg	grp = NULL;
64721826Sjoerg	nameorID = "named";
64821826Sjoerg	errno = 0;
64921826Sjoerg	bigtemp = strtoul(elem, &endp, 10);
65021826Sjoerg	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
65121826Sjoerg		nameorID = "name or ID matches";
65221826Sjoerg		grp = getgrgid((gid_t)bigtemp);
65321826Sjoerg	}
65421826Sjoerg	if (grp == NULL)
65521826Sjoerg		grp = getgrnam(elem);
65693383Smdodd	if (grp == NULL) {
65721826Sjoerg		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
65893383Smdodd		optfatal = 1;
65921826Sjoerg		return (0);
66021826Sjoerg	}
66121826Sjoerg	if (inf->count >= inf->maxcount)
66293383Smdodd		expand_list(inf);
66393383Smdodd	inf->l.gids[(inf->count)++] = grp->gr_gid;
66493383Smdodd	return (1);
66593383Smdodd}
66693383Smdodd
66793383Smdodd#define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h. */
66893383Smdoddstatic int
66993383Smdoddaddelem_pid(struct listinfo *inf, const char *elem)
67093383Smdodd{
67193383Smdodd	char *endp;
67293383Smdodd	long tempid;
67393383Smdodd
67493383Smdodd	if (*elem == '\0') {
67593383Smdodd		warnx("Invalid (zero-length) process id");
67693383Smdodd		optfatal = 1;
67793383Smdodd		return (0);		/* Do not add this value. */
67893383Smdodd	}
67993383Smdodd
68093383Smdodd	errno = 0;
68193383Smdodd	tempid = strtol(elem, &endp, 10);
68293383Smdodd	if (*endp != '\0' || tempid < 0 || elem == endp) {
68393383Smdodd		warnx("Invalid %s: %s", inf->lname, elem);
68421826Sjoerg		errno = ERANGE;
68521826Sjoerg	} else if (errno != 0 || tempid > BSD_PID_MAX) {
68621826Sjoerg		warnx("%s too large: %s", inf->lname, elem);
68721826Sjoerg		errno = ERANGE;
68821826Sjoerg	}
68921826Sjoerg	if (errno == ERANGE) {
69021826Sjoerg		optfatal = 1;
69121826Sjoerg		return (0);
69221826Sjoerg	}
69321826Sjoerg	if (inf->count >= inf->maxcount)
69421826Sjoerg		expand_list(inf);
69521826Sjoerg	inf->l.pids[(inf->count)++] = tempid;
69621826Sjoerg	return (1);
69793383Smdodd}
69821826Sjoerg#undef	BSD_PID_MAX
69921826Sjoerg
70021826Sjoergstatic int
70121826Sjoergaddelem_tty(struct listinfo *inf, const char *elem)
70221826Sjoerg{
70321826Sjoerg	const char *ttypath;
70421826Sjoerg	struct stat sb;
70521826Sjoerg	char pathbuf[PATH_MAX];
70621826Sjoerg
70721826Sjoerg	if (strcmp(elem, "co") == 0)
70821826Sjoerg		ttypath = strdup(_PATH_CONSOLE);
70921826Sjoerg	else if (*elem == '/')
71021826Sjoerg		ttypath = elem;
71121826Sjoerg	else {
71221826Sjoerg		strlcpy(pathbuf, _PATH_TTY, sizeof(pathbuf));
71321826Sjoerg		strlcat(pathbuf, elem, sizeof(pathbuf));
71421826Sjoerg		ttypath = pathbuf;
71521826Sjoerg	}
71621826Sjoerg
71721826Sjoerg	if (stat(ttypath, &sb) == -1) {
71821826Sjoerg		warn("%s", ttypath);
71921826Sjoerg		optfatal = 1;
72021826Sjoerg		return (0);
72121826Sjoerg	}
72221826Sjoerg	if (!S_ISCHR(sb.st_mode)) {
72321826Sjoerg		warn("%s: Not a terminal", ttypath);
72421826Sjoerg		optfatal = 1;
72521826Sjoerg		return (0);
72621826Sjoerg	}
72721826Sjoerg	if (inf->count >= inf->maxcount)
72821826Sjoerg		expand_list(inf);
72921826Sjoerg	inf->l.ttys[(inf->count)++] = sb.st_rdev;
73021826Sjoerg	return (1);
73121826Sjoerg}
73221826Sjoerg
73321826Sjoergstatic int
73493383Smdoddaddelem_uid(struct listinfo *inf, const char *elem)
73521826Sjoerg{
73621826Sjoerg	struct passwd *pwd;
73793383Smdodd	char *endp;
73893383Smdodd	u_long bigtemp;
73993383Smdodd
74093383Smdodd	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
74121826Sjoerg		if (*elem == '\0')
74221826Sjoerg			warnx("Invalid (zero-length) %s name", inf->lname);
74321826Sjoerg		else
74421826Sjoerg			warnx("%s name too long: %s", inf->lname, elem);
74521826Sjoerg		optfatal = 1;
74621826Sjoerg		return (0);		/* Do not add this value. */
74721826Sjoerg	}
74821826Sjoerg
74921826Sjoerg	pwd = getpwnam(elem);
75021826Sjoerg	if (pwd == NULL) {
75121826Sjoerg		errno = 0;
75221826Sjoerg		bigtemp = strtoul(elem, &endp, 10);
75321826Sjoerg		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
75421826Sjoerg			warnx("No %s named '%s'", inf->lname, elem);
75521826Sjoerg		else {
75621826Sjoerg			/* The string is all digits, so it might be a userID. */
75721826Sjoerg			pwd = getpwuid((uid_t)bigtemp);
75821826Sjoerg			if (pwd == NULL)
75921826Sjoerg				warnx("No %s name or ID matches '%s'",
76021826Sjoerg				    inf->lname, elem);
76121826Sjoerg		}
76221826Sjoerg	}
76321826Sjoerg	if (pwd == NULL) {
76421826Sjoerg		/*
76521826Sjoerg		 * These used to be treated as minor warnings (and the
76621826Sjoerg		 * option was simply ignored), but now they are fatal
76793383Smdodd		 * errors (and the command will be aborted).
76893383Smdodd		 */
76993383Smdodd		optfatal = 1;
77021826Sjoerg		return (0);
77121826Sjoerg	}
77221826Sjoerg	if (inf->count >= inf->maxcount)
77321826Sjoerg		expand_list(inf);
77421826Sjoerg	inf->l.uids[(inf->count)++] = pwd->pw_uid;
77521826Sjoerg	return (1);
77693383Smdodd}
77721826Sjoerg
77821826Sjoergstatic void
77993383Smdoddadd_list(struct listinfo *inf, const char *argp)
78021826Sjoerg{
78121826Sjoerg	const char *savep;
78221826Sjoerg	char *cp, *endp;
78321826Sjoerg	int toolong;
78421826Sjoerg	char elemcopy[PATH_MAX];
78521826Sjoerg
78621826Sjoerg	if (*argp == 0)
78721826Sjoerg		inf->addelem(inf, elemcopy);
78821826Sjoerg	while (*argp != '\0') {
78921826Sjoerg		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
79021826Sjoerg			argp++;
79121826Sjoerg		savep = argp;
79293383Smdodd		toolong = 0;
79321826Sjoerg		cp = elemcopy;
79421826Sjoerg		if (strchr(T_SEP, *argp) == NULL) {
79521826Sjoerg			endp = elemcopy + sizeof(elemcopy) - 1;
79693383Smdodd			while (*argp != '\0' && cp <= endp &&
79721826Sjoerg			    strchr(W_SEP T_SEP, *argp) == NULL)
79893383Smdodd				*cp++ = *argp++;
79993383Smdodd			if (cp > endp)
80093383Smdodd				toolong = 1;
80193383Smdodd		}
80293383Smdodd		if (!toolong) {
80321826Sjoerg			*cp = '\0';
80421826Sjoerg			/*
80521826Sjoerg			 * Add this single element to the given list.
80621826Sjoerg			 */
80721826Sjoerg			inf->addelem(inf, elemcopy);
80821826Sjoerg		} else {
80921826Sjoerg			/*
81021826Sjoerg			 * The string is too long to copy.  Find the end
81121826Sjoerg			 * of the string to print out the warning message.
81221826Sjoerg			 */
81346568Speter			while (*argp != '\0' && strchr(W_SEP T_SEP,
81421826Sjoerg			    *argp) == NULL)
81593383Smdodd				argp++;
81693383Smdodd			warnx("Value too long: %.*s", (int)(argp - savep),
81793383Smdodd			    savep);
81893383Smdodd			optfatal = 1;
81993383Smdodd		}
82093383Smdodd		/*
82193383Smdodd		 * Skip over any number of trailing whitespace characters,
82293383Smdodd		 * but only one (at most) trailing element-terminating
82393383Smdodd		 * character.
82493383Smdodd		 */
82593383Smdodd		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
82693383Smdodd			argp++;
82793383Smdodd		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
82893383Smdodd			argp++;
82993383Smdodd			/* Catch case where string ended with a comma. */
83046568Speter			if (*argp == '\0')
83121826Sjoerg				inf->addelem(inf, argp);
83221826Sjoerg		}
83321826Sjoerg	}
83421826Sjoerg}
83521826Sjoerg
83621826Sjoergstatic void *
83721826Sjoergexpand_list(struct listinfo *inf)
83821826Sjoerg{
83921826Sjoerg	void *newlist;
84021826Sjoerg	int newmax;
84121826Sjoerg
84221826Sjoerg	newmax = (inf->maxcount + 1) << 1;
84321826Sjoerg	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
84421826Sjoerg	if (newlist == NULL) {
84521826Sjoerg		free(inf->l.ptr);
84621826Sjoerg		errx(1, "realloc to %d %ss failed", newmax, inf->lname);
84721826Sjoerg	}
84893383Smdodd	inf->maxcount = newmax;
84993383Smdodd	inf->l.ptr = newlist;
85093383Smdodd
85121826Sjoerg	return (newlist);
85221826Sjoerg}
85321826Sjoerg
85421826Sjoergstatic void
85521826Sjoergfree_list(struct listinfo *inf)
85621826Sjoerg{
85721826Sjoerg
85821826Sjoerg	inf->count = inf->elemsize = inf->maxcount = 0;
85921826Sjoerg	if (inf->l.ptr != NULL)
86021826Sjoerg		free(inf->l.ptr);
86121826Sjoerg	inf->addelem = NULL;
86221826Sjoerg	inf->lname = NULL;
86321826Sjoerg	inf->l.ptr = NULL;
86421826Sjoerg}
86521826Sjoerg
86621826Sjoergstatic void
86793383Smdoddinit_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
86821826Sjoerg    const char *lname)
86921826Sjoerg{
87021826Sjoerg
87121826Sjoerg	inf->count = inf->maxcount = 0;
87221826Sjoerg	inf->elemsize = elemsize;
87321826Sjoerg	inf->addelem = artn;
87421826Sjoerg	inf->lname = lname;
87521826Sjoerg	inf->l.ptr = NULL;
87621826Sjoerg}
87721826Sjoerg
87821826SjoergVARENT *
87921826Sjoergfind_varentry(VAR *v)
88093383Smdodd{
88193383Smdodd	struct varent *vent;
88293383Smdodd
88321826Sjoerg	for (vent = vhead; vent; vent = vent->next) {
88421826Sjoerg		if (strcmp(vent->var->name, v->name) == 0)
88521826Sjoerg			return vent;
88621826Sjoerg	}
88721826Sjoerg	return NULL;
88821826Sjoerg}
88921826Sjoerg
89021826Sjoergstatic void
89121826Sjoergscanvars(void)
89221826Sjoerg{
89321826Sjoerg	struct varent *vent;
89421826Sjoerg	VAR *v;
89521826Sjoerg
89621826Sjoerg	for (vent = vhead; vent; vent = vent->next) {
89793383Smdodd		v = vent->var;
89893383Smdodd		if (v->flag & DSIZ) {
89921826Sjoerg			v->dwidth = v->width;
90021826Sjoerg			v->width = 0;
90121826Sjoerg		}
90221826Sjoerg		if (v->flag & USER)
90321826Sjoerg			needuser = 1;
90493383Smdodd		if (v->flag & COMM)
90593383Smdodd			needcomm = 1;
90621826Sjoerg	}
90721826Sjoerg}
90821826Sjoerg
90921826Sjoergstatic void
91093383Smdodddynsizevars(KINFO *ki)
91193383Smdodd{
91293383Smdodd	struct varent *vent;
91321826Sjoerg	VAR *v;
91493383Smdodd	int i;
91593383Smdodd
91693383Smdodd	for (vent = vhead; vent; vent = vent->next) {
91793383Smdodd		v = vent->var;
91893383Smdodd		if (!(v->flag & DSIZ))
91993383Smdodd			continue;
92093383Smdodd		i = (v->sproc)( ki);
92193383Smdodd		if (v->width < i)
92293383Smdodd			v->width = i;
92393383Smdodd		if (v->width > v->dwidth)
92493383Smdodd			v->width = v->dwidth;
92593383Smdodd	}
92621826Sjoerg}
92793383Smdodd
92821826Sjoergstatic void
92993383Smdoddsizevars(void)
93093383Smdodd{
93193383Smdodd	struct varent *vent;
93293383Smdodd	VAR *v;
93393383Smdodd	int i;
93421826Sjoerg
93593383Smdodd	for (vent = vhead; vent; vent = vent->next) {
93693383Smdodd		v = vent->var;
93793383Smdodd		i = strlen(vent->header);
93893383Smdodd		if (v->width < i)
93993383Smdodd			v->width = i;
94093383Smdodd		totwidth += v->width + 1;	/* +1 for space */
94193383Smdodd	}
94293383Smdodd	totwidth--;
94393383Smdodd}
94493383Smdodd
94593383Smdoddstatic const char *
94693383Smdoddfmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
94793383Smdodd    char *comm, int maxlen)
94893383Smdodd{
94993383Smdodd	const char *s;
95093383Smdodd
95193383Smdodd	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
95293383Smdodd	return (s);
95393383Smdodd}
95493383Smdodd
95593383Smdodd#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
95621826Sjoerg
95721826Sjoergstatic void
95821826Sjoergsaveuser(KINFO *ki)
95921826Sjoerg{
96021826Sjoerg
96121826Sjoerg	if (ki->ki_p->ki_sflag & PS_INMEM) {
96221826Sjoerg		/*
96321826Sjoerg		 * The u-area might be swapped out, and we can't get
96421826Sjoerg		 * at it because we have a crashdump and no swap.
96521826Sjoerg		 * If it's here fill in these fields, otherwise, just
96621826Sjoerg		 * leave them 0.
96721826Sjoerg		 */
96821826Sjoerg		ki->ki_valid = 1;
96921826Sjoerg	} else
97021826Sjoerg		ki->ki_valid = 0;
97121826Sjoerg	/*
97221826Sjoerg	 * save arguments if needed
97321826Sjoerg	 */
97493383Smdodd	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
97521826Sjoerg		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
97693383Smdodd		    MAXCOMLEN));
97721826Sjoerg	} else if (needcomm) {
97821826Sjoerg		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
97921826Sjoerg	} else {
98021826Sjoerg		ki->ki_args = NULL;
98121826Sjoerg	}
98221826Sjoerg	if (needenv && UREADOK(ki)) {
98321826Sjoerg		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
98421826Sjoerg	} else if (needenv) {
98593383Smdodd		ki->ki_env = malloc(3);
98621826Sjoerg		strcpy(ki->ki_env, "()");
98793383Smdodd	} else {
98821826Sjoerg		ki->ki_env = NULL;
98993383Smdodd	}
99093383Smdodd}
99193383Smdodd
99293383Smdoddstatic int
99393383Smdoddpscomp(const void *a, const void *b)
99493383Smdodd{
99593383Smdodd	const KINFO *ka, *kb;
99621826Sjoerg	double cpua, cpub;
99721826Sjoerg	segsz_t sizea, sizeb;
99821826Sjoerg
99921826Sjoerg	ka = a;
100021826Sjoerg	kb = b;
100193383Smdodd	/* SORTCPU and SORTMEM are sorted in descending order. */
100293383Smdodd	if (sortby == SORTCPU) {
100321826Sjoerg		cpua = getpcpu(ka);
100421826Sjoerg		cpub = getpcpu(kb);
100521826Sjoerg		if (cpua < cpub)
100621826Sjoerg			return (1);
100721826Sjoerg		if (cpua > cpub)
100821826Sjoerg			return (-1);
100993383Smdodd	}
101093383Smdodd	if (sortby == SORTMEM) {
101193383Smdodd		sizea = ka->ki_p->ki_tsize + ka->ki_p->ki_dsize +
101293383Smdodd		    ka->ki_p->ki_ssize;
101393383Smdodd		sizeb = kb->ki_p->ki_tsize + kb->ki_p->ki_dsize +
101421826Sjoerg		    kb->ki_p->ki_ssize;
101593383Smdodd		if (sizea < sizeb)
101621826Sjoerg			return (1);
101721826Sjoerg		if (sizea > sizeb)
101821826Sjoerg			return (-1);
101921826Sjoerg	}
102021826Sjoerg	/*
102121826Sjoerg	 * TTY's are sorted in ascending order, except that all NODEV
102221826Sjoerg	 * processes come before all processes with a device.
102321826Sjoerg	 */
102421826Sjoerg	if (ka->ki_p->ki_tdev == NODEV && kb->ki_p->ki_tdev != NODEV)
102521826Sjoerg		return (-1);
102621826Sjoerg	if (ka->ki_p->ki_tdev != NODEV && kb->ki_p->ki_tdev == NODEV)
102721826Sjoerg		return (1);
102821826Sjoerg	if (ka->ki_p->ki_tdev < kb->ki_p->ki_tdev)
102921826Sjoerg		return (-1);
103021826Sjoerg	if (ka->ki_p->ki_tdev > kb->ki_p->ki_tdev)
103193383Smdodd		return (1);
103221826Sjoerg	/* PID's are sorted in ascending order. */
103321826Sjoerg	if (ka->ki_p->ki_pid < kb->ki_p->ki_pid)
103421826Sjoerg		return (-1);
103521826Sjoerg	if (ka->ki_p->ki_pid > kb->ki_p->ki_pid)
103621826Sjoerg		return (1);
103721826Sjoerg	return (0);
103821826Sjoerg}
103921826Sjoerg
104021826Sjoerg/*
104193383Smdodd * ICK (all for getopt), would rather hide the ugliness
104221826Sjoerg * here than taint the main code.
104321826Sjoerg *
104421826Sjoerg *  ps foo -> ps -foo
104521826Sjoerg *  ps 34 -> ps -p34
104693383Smdodd *
104793383Smdodd * The old convention that 't' with no trailing tty arg means the users
104821826Sjoerg * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
104921826Sjoerg * feature is available with the option 'T', which takes no argument.
105093383Smdodd */
105193383Smdoddstatic char *
105221826Sjoergkludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
105321826Sjoerg{
105421826Sjoerg	size_t len;
105521826Sjoerg	char *argp, *cp, *newopts, *ns, *optp, *pidp;
105621826Sjoerg
105721826Sjoerg	/*
105821826Sjoerg	 * See if the original value includes any option which takes an
105921826Sjoerg	 * argument (and will thus use up the remainder of the string).
106021826Sjoerg	 */
106121826Sjoerg	argp = NULL;
106221826Sjoerg	if (optlist != NULL) {
106321826Sjoerg		for (cp = origval; *cp != '\0'; cp++) {
106421826Sjoerg			optp = strchr(optlist, *cp);
106521826Sjoerg			if ((optp != NULL) && *(optp + 1) == ':') {
106621826Sjoerg				argp = cp;
106721826Sjoerg				break;
106821826Sjoerg			}
106921826Sjoerg		}
107093383Smdodd	}
107121826Sjoerg	if (argp != NULL && *origval == '-')
107221826Sjoerg		return (origval);
107321826Sjoerg
107493383Smdodd	/*
107593383Smdodd	 * if last letter is a 't' flag with no argument (in the context
107621826Sjoerg	 * of the oldps options -- option string NOT starting with a '-' --
107721826Sjoerg	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
107821826Sjoerg	 *
107921826Sjoerg	 * However, if a flag accepting a string argument is found earlier
108021826Sjoerg	 * in the option string (including a possible `t' flag), then the
108121826Sjoerg	 * remainder of the string must be the argument to that flag; so
108221826Sjoerg	 * do not modify that argument.  Note that a trailing `t' would
108321826Sjoerg	 * cause argp to be set, if argp was not already set by some
108421826Sjoerg	 * earlier option.
108521826Sjoerg	 */
108621826Sjoerg	len = strlen(origval);
108721826Sjoerg	cp = origval + len - 1;
108821826Sjoerg	pidp = NULL;
108921826Sjoerg	if (*cp == 't' && *origval != '-' && cp == argp) {
109021826Sjoerg		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
109121826Sjoerg			*cp = 'T';
109293383Smdodd	} else if (argp == NULL) {
109321826Sjoerg		/*
109421826Sjoerg		 * The original value did not include any option which takes
109521826Sjoerg		 * an argument (and that would include `p' and `t'), so check
109693383Smdodd		 * the value for trailing number, or comma-separated list of
109721826Sjoerg		 * numbers, which we will treat as a pid request.
109821826Sjoerg		 */
109921826Sjoerg		if (isdigitch(*cp)) {
110021826Sjoerg			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
110121826Sjoerg				--cp;
110293383Smdodd			pidp = cp + 1;
110321826Sjoerg		}
110421826Sjoerg	}
110521826Sjoerg
110621826Sjoerg	/*
110721826Sjoerg	 * If nothing needs to be added to the string, then return
110821826Sjoerg	 * the "original" (although possibly modified) value.
110921826Sjoerg	 */
111021826Sjoerg	if (*origval == '-' && pidp == NULL)
111121826Sjoerg		return (origval);
111221826Sjoerg
111321826Sjoerg	/*
111421826Sjoerg	 * Create a copy of the string to add '-' and/or 'p' to the
111521826Sjoerg	 * original value.
111621826Sjoerg	 */
111721826Sjoerg	if ((newopts = ns = malloc(len + 3)) == NULL)
111821826Sjoerg		errx(1, "malloc failed");
111921826Sjoerg
112021826Sjoerg	if (*origval != '-')
112121826Sjoerg		*ns++ = '-';	/* add option flag */
112221826Sjoerg
112321826Sjoerg	if (pidp == NULL)
112421826Sjoerg		strcpy(ns, origval);
112521826Sjoerg	else {
112621826Sjoerg		/*
112721826Sjoerg		 * Copy everything before the pid string, add the `p',
112821826Sjoerg		 * and then copy the pid string.
112921826Sjoerg		 */
113021826Sjoerg		len = pidp - origval;
113121826Sjoerg		memcpy(ns, origval, len);
113221826Sjoerg		ns += len;
113321826Sjoerg		*ns++ = 'p';
113421826Sjoerg		strcpy(ns, pidp);
113521826Sjoerg	}
113621826Sjoerg
113721826Sjoerg	return (newopts);
113821826Sjoerg}
1139102412Scharnier
114021826Sjoergstatic void
114121826Sjoergusage(void)
114221826Sjoerg{
114321826Sjoerg#define	SINGLE_OPTS	"[-aC" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
114421826Sjoerg
114521826Sjoerg	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
114621826Sjoerg	    "usage: ps " SINGLE_OPTS " [-G gid[,gid]] [-O|o fmt]",
1147102412Scharnier	    "          [-p pid[,pid]] [-t tty[,tty]] [-U user[,user]]",
114821826Sjoerg	    "          [-M core] [-N system]",
114921826Sjoerg	    "       ps [-L]");
115021826Sjoerg	exit(1);
115121826Sjoerg}
115221826Sjoerg