ps.c revision 203688
199357Smarkm/*-
299357Smarkm * Copyright (c) 1990, 1993, 1994
399357Smarkm *	The Regents of the University of California.  All rights reserved.
499357Smarkm *
599357Smarkm * Redistribution and use in source and binary forms, with or without
699357Smarkm * modification, are permitted provided that the following conditions
799357Smarkm * are met:
899357Smarkm * 1. Redistributions of source code must retain the above copyright
999357Smarkm *    notice, this list of conditions and the following disclaimer.
1099357Smarkm * 2. Redistributions in binary form must reproduce the above copyright
1199357Smarkm *    notice, this list of conditions and the following disclaimer in the
1299357Smarkm *    documentation and/or other materials provided with the distribution.
1399357Smarkm * 4. Neither the name of the University nor the names of its contributors
1499357Smarkm *    may be used to endorse or promote products derived from this software
1599357Smarkm *    without specific prior written permission.
1699357Smarkm *
1799357Smarkm * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1899357Smarkm * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1999357Smarkm * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2099357Smarkm * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2199357Smarkm * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2299357Smarkm * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2399357Smarkm * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2499357Smarkm * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2599357Smarkm * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2699357Smarkm * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2799357Smarkm * SUCH DAMAGE.
2899357Smarkm * ------+---------+---------+-------- + --------+---------+---------+---------*
2999357Smarkm * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
3099357Smarkm * All rights reserved.
3199357Smarkm *
32270309Sse * Significant modifications made to bring `ps' options somewhat closer
3399357Smarkm * to the standard for `ps' as described in SingleUnixSpec-v3.
3499357Smarkm * ------+---------+---------+-------- + --------+---------+---------+---------*
3599357Smarkm */
3699357Smarkm
37106053Swollman#ifndef lint
3899357Smarkmstatic const char copyright[] =
3999357Smarkm"@(#) Copyright (c) 1990, 1993, 1994\n\
4099357Smarkm	The Regents of the University of California.  All rights reserved.\n";
4199357Smarkm#endif /* not lint */
4299357Smarkm
4399357Smarkm#if 0
4499357Smarkm#ifndef lint
4599357Smarkmstatic char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
4699357Smarkm#endif /* not lint */
4799357Smarkm#endif
4899357Smarkm
4999357Smarkm#include <sys/cdefs.h>
5099357Smarkm__FBSDID("$FreeBSD: head/bin/ps/ps.c 203688 2010-02-08 21:23:48Z brucec $");
51270309Sse
52270309Sse#include <sys/param.h>
53270309Sse#include <sys/proc.h>
5499357Smarkm#include <sys/user.h>
5599357Smarkm#include <sys/stat.h>
5699357Smarkm#include <sys/ioctl.h>
5799357Smarkm#include <sys/sysctl.h>
5899357Smarkm#include <sys/mount.h>
5999357Smarkm
60293335Semaste#include <ctype.h>
6199357Smarkm#include <err.h>
6299357Smarkm#include <errno.h>
6399357Smarkm#include <fcntl.h>
6499357Smarkm#include <grp.h>
6599357Smarkm#include <kvm.h>
6699357Smarkm#include <limits.h>
6799357Smarkm#include <locale.h>
6899357Smarkm#include <paths.h>
6999357Smarkm#include <pwd.h>
7099357Smarkm#include <stdio.h>
7199357Smarkm#include <stdlib.h>
7299357Smarkm#include <string.h>
7399357Smarkm#include <unistd.h>
7499357Smarkm
7599357Smarkm#include "ps.h"
7699357Smarkm
7799357Smarkm#define	_PATH_PTS	"/dev/pts/"
7899357Smarkm
7999357Smarkm#define	W_SEP	" \t"		/* "Whitespace" list separators */
8099357Smarkm#define	T_SEP	","		/* "Terminate-element" list separators */
8199357Smarkm
8299357Smarkm#ifdef LAZY_PS
8399357Smarkm#define	DEF_UREAD	0
8499357Smarkm#define	OPT_LAZY_f	"f"
8599357Smarkm#else
8699357Smarkm#define	DEF_UREAD	1	/* Always do the more-expensive read. */
8799357Smarkm#define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
8899357Smarkm#endif
8999357Smarkm
9099357Smarkm/*
9199357Smarkm * isdigit takes an `int', but expects values in the range of unsigned char.
9299357Smarkm * This wrapper ensures that values from a 'char' end up in the correct range.
9399357Smarkm */
9499357Smarkm#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
9599357Smarkm
9699357Smarkmint	 cflag;			/* -c */
9799357Smarkmint	 eval;			/* Exit value */
9899357Smarkmtime_t	 now;			/* Current time(3) value */
9999357Smarkmint	 rawcpu;		/* -C */
10099357Smarkmint	 sumrusage;		/* -S */
10199357Smarkmint	 termwidth;		/* Width of the screen (0 == infinity). */
10299357Smarkmint	 totwidth;		/* Calculated-width of requested variables. */
10399357Smarkmint	 showthreads;		/* will threads be shown? */
10499357Smarkm
10599357Smarkmstruct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
10699357Smarkm
10799357Smarkmstatic int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
10899357Smarkmstatic kvm_t	*kd;
10999357Smarkmstatic KINFO	*kinfo;
11099357Smarkmstatic int	 needcomm;	/* -o "command" */
11199357Smarkmstatic int	 needenv;	/* -e */
11299357Smarkmstatic int	 needuser;	/* -o "user" */
11399357Smarkmstatic int	 optfatal;	/* Fatal error parsing some list-option. */
11499357Smarkm
11599357Smarkmstatic enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
11699357Smarkm
11799357Smarkmstruct listinfo;
11899357Smarkmtypedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
11999357Smarkm
12099357Smarkmstruct listinfo {
12199357Smarkm	int		 count;
12299357Smarkm	int		 maxcount;
12399357Smarkm	int		 elemsize;
12499357Smarkm	addelem_rtn	*addelem;
12599357Smarkm	const char	*lname;
12699357Smarkm	union {
12799357Smarkm		gid_t	*gids;
12899357Smarkm		pid_t	*pids;
12999357Smarkm		dev_t	*ttys;
13099357Smarkm		uid_t	*uids;
13199357Smarkm		void	*ptr;
13299357Smarkm	} l;
13399357Smarkm};
13499357Smarkm
13599357Smarkmstatic int	 check_procfs(void);
13699357Smarkmstatic int	 addelem_gid(struct listinfo *, const char *);
13799357Smarkmstatic int	 addelem_pid(struct listinfo *, const char *);
13899357Smarkmstatic int	 addelem_tty(struct listinfo *, const char *);
13999357Smarkmstatic int	 addelem_uid(struct listinfo *, const char *);
14099357Smarkmstatic void	 add_list(struct listinfo *, const char *);
14199357Smarkmstatic void	 descendant_sort(KINFO *, int);
14299357Smarkmstatic void	 dynsizevars(KINFO *);
14399357Smarkmstatic void	*expand_list(struct listinfo *);
14499357Smarkmstatic const char *
14599357Smarkm		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
14699357Smarkm		    KINFO *, char *, int);
14799357Smarkmstatic void	 free_list(struct listinfo *);
14899357Smarkmstatic void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
14999357Smarkmstatic char	*kludge_oldps_options(const char *, char *, const char *);
15099357Smarkmstatic int	 pscomp(const void *, const void *);
151270309Ssestatic void	 saveuser(KINFO *);
152270309Ssestatic void	 scanvars(void);
153270309Ssestatic void	 sizevars(void);
154293335Semastestatic void	 usage(void);
155270309Sse
156270309Ssestatic char dfmt[] = "pid,tt,state,time,command";
157270309Ssestatic char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
158270309Ssestatic char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
159270309Sse			"tt,time,command";
160270309Ssestatic char   o1[] = "pid";
161270309Ssestatic char   o2[] = "tt,state,time,command";
162270309Ssestatic char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
163293335Semastestatic char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
164270309Sse			"%cpu,%mem,command";
165270309Ssestatic char Zfmt[] = "label";
166270309Sse
16799357Smarkm#define	PS_ARGS	"AaCcde" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
16899357Smarkm
16999357Smarkmint
17099357Smarkmmain(int argc, char *argv[])
17199357Smarkm{
17299357Smarkm	struct listinfo gidlist, pgrplist, pidlist;
17399357Smarkm	struct listinfo ruidlist, sesslist, ttylist, uidlist;
17499357Smarkm	struct kinfo_proc *kp;
17599357Smarkm	KINFO *next_KINFO;
17699357Smarkm	struct varent *vent;
17799357Smarkm	struct winsize ws;
17899357Smarkm	const char *nlistf, *memf;
17999357Smarkm	char *cols;
18099357Smarkm	int all, ch, elem, flag, _fmt, i, lineno;
18199357Smarkm	int descendancy, nentries, nkept, nselectors;
18299357Smarkm	int prtheader, wflag, what, xkeep, xkeep_implied;
18399357Smarkm	char errbuf[_POSIX2_LINE_MAX];
18499357Smarkm
18599357Smarkm	(void) setlocale(LC_ALL, "");
18699357Smarkm	time(&now);			/* Used by routines in print.c. */
18799357Smarkm
18899357Smarkm	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
18999357Smarkm		termwidth = atoi(cols);
19099357Smarkm	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
19199357Smarkm	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
19299357Smarkm	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
19399357Smarkm	     ws.ws_col == 0)
19499357Smarkm		termwidth = 79;
19599357Smarkm	else
19699357Smarkm		termwidth = ws.ws_col - 1;
19799357Smarkm
19899357Smarkm	/*
19999357Smarkm	 * Hide a number of option-processing kludges in a separate routine,
20099357Smarkm	 * to support some historical BSD behaviors, such as `ps axu'.
20199357Smarkm	 */
20299357Smarkm	if (argc > 1)
20399357Smarkm		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
20499357Smarkm
20599357Smarkm	all = descendancy = _fmt = nselectors = optfatal = 0;
20699357Smarkm	prtheader = showthreads = wflag = xkeep_implied = 0;
20799357Smarkm	xkeep = -1;			/* Neither -x nor -X. */
20899357Smarkm	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
20999357Smarkm	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
21099357Smarkm	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
21199357Smarkm	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
21299357Smarkm	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
21399357Smarkm	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
21499357Smarkm	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
21599357Smarkm	memf = _PATH_DEVNULL;
21699357Smarkm	nlistf = NULL;
21799357Smarkm	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
21899357Smarkm		switch (ch) {
21999357Smarkm		case 'A':
22099357Smarkm			/*
22199357Smarkm			 * Exactly the same as `-ax'.   This has been
22299357Smarkm			 * added for compatability with SUSv3, but for
22399357Smarkm			 * now it will not be described in the man page.
22499357Smarkm			 */
22599357Smarkm			nselectors++;
22699357Smarkm			all = xkeep = 1;
22799357Smarkm			break;
22899357Smarkm		case 'a':
22999357Smarkm			nselectors++;
23099357Smarkm			all = 1;
23199357Smarkm			break;
23299357Smarkm		case 'C':
23399357Smarkm			rawcpu = 1;
23499357Smarkm			break;
23599357Smarkm		case 'c':
23699357Smarkm			cflag = 1;
23799357Smarkm			break;
23899357Smarkm		case 'd':
23999357Smarkm			descendancy = 1;
24099357Smarkm			break;
24199357Smarkm		case 'e':			/* XXX set ufmt */
24299357Smarkm			needenv = 1;
24399357Smarkm			break;
24499357Smarkm#ifdef LAZY_PS
24599357Smarkm		case 'f':
24699357Smarkm			if (getuid() == 0 || getgid() == 0)
247222568Sjh				forceuread = 1;
24899357Smarkm			break;
24999357Smarkm#endif
25099357Smarkm		case 'G':
25199357Smarkm			add_list(&gidlist, optarg);
25299357Smarkm			xkeep_implied = 1;
25399357Smarkm			nselectors++;
25499357Smarkm			break;
25599357Smarkm		case 'g':
25699357Smarkm#if 0
25799357Smarkm			/*-
25899357Smarkm			 * XXX - This SUSv3 behavior is still under debate
25999357Smarkm			 *	since it conflicts with the (undocumented)
260293335Semaste			 *	`-g' option.  So we skip it for now.
26199357Smarkm			 */
26299357Smarkm			add_list(&pgrplist, optarg);
26399357Smarkm			xkeep_implied = 1;
26499357Smarkm			nselectors++;
26599357Smarkm			break;
26699357Smarkm#else
26799357Smarkm			/* The historical BSD-ish (from SunOS) behavior. */
268293335Semaste			break;			/* no-op */
269293335Semaste#endif
270293335Semaste		case 'H':
271293335Semaste			showthreads = KERN_PROC_INC_THREAD;
272293335Semaste			break;
273293335Semaste		case 'h':
274293335Semaste			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
27599357Smarkm			break;
27699357Smarkm		case 'j':
27799357Smarkm			parsefmt(jfmt, 0);
27899357Smarkm			_fmt = 1;
27999357Smarkm			jfmt[0] = '\0';
28099357Smarkm			break;
28199357Smarkm		case 'L':
28299357Smarkm			showkey();
28399357Smarkm			exit(0);
28499357Smarkm		case 'l':
28599357Smarkm			parsefmt(lfmt, 0);
28699357Smarkm			_fmt = 1;
28799357Smarkm			lfmt[0] = '\0';
28899357Smarkm			break;
28999357Smarkm		case 'M':
29099357Smarkm			memf = optarg;
29199357Smarkm			break;
29299357Smarkm		case 'm':
29399357Smarkm			sortby = SORTMEM;
29499357Smarkm			break;
29599357Smarkm		case 'N':
29699357Smarkm			nlistf = optarg;
29799357Smarkm			break;
29899357Smarkm		case 'O':
29999357Smarkm			parsefmt(o1, 1);
30099357Smarkm			parsefmt(optarg, 1);
30199357Smarkm			parsefmt(o2, 1);
30299357Smarkm			o1[0] = o2[0] = '\0';
30399357Smarkm			_fmt = 1;
30499357Smarkm			break;
30599357Smarkm		case 'o':
30699357Smarkm			parsefmt(optarg, 1);
30799357Smarkm			_fmt = 1;
30899357Smarkm			break;
30999357Smarkm		case 'p':
31099357Smarkm			add_list(&pidlist, optarg);
31199357Smarkm			/*
31299357Smarkm			 * Note: `-p' does not *set* xkeep, but any values
31399357Smarkm			 * from pidlist are checked before xkeep is.  That
31499357Smarkm			 * way they are always matched, even if the user
31599357Smarkm			 * specifies `-X'.
316226439Snwhitehorn			 */
31799357Smarkm			nselectors++;
31899357Smarkm			break;
31999357Smarkm#if 0
32099357Smarkm		case 'R':
32199357Smarkm			/*-
32299357Smarkm			 * XXX - This un-standard option is still under
32399357Smarkm			 *	debate.  This is what SUSv3 defines as
32499357Smarkm			 *	the `-U' option, and while it would be
32599357Smarkm			 *	nice to have, it could cause even more
32699357Smarkm			 *	confusion to implement it as `-R'.
32799357Smarkm			 */
32899357Smarkm			add_list(&ruidlist, optarg);
32999357Smarkm			xkeep_implied = 1;
33099357Smarkm			nselectors++;
33199357Smarkm			break;
33299357Smarkm#endif
33399357Smarkm		case 'r':
33499357Smarkm			sortby = SORTCPU;
33599357Smarkm			break;
33699357Smarkm		case 'S':
33799357Smarkm			sumrusage = 1;
33899357Smarkm			break;
33999357Smarkm#if 0
34099357Smarkm		case 's':
34199357Smarkm			/*-
34299357Smarkm			 * XXX - This non-standard option is still under
34399357Smarkm			 *	debate.  This *is* supported on Solaris,
34499357Smarkm			 *	Linux, and IRIX, but conflicts with `-s'
34599357Smarkm			 *	on NetBSD and maybe some older BSD's.
34699357Smarkm			 */
34799357Smarkm			add_list(&sesslist, optarg);
34899357Smarkm			xkeep_implied = 1;
34999357Smarkm			nselectors++;
35099357Smarkm			break;
35199357Smarkm#endif
35299357Smarkm		case 'T':
35399357Smarkm			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
35499357Smarkm				errx(1, "stdin: not a terminal");
35599357Smarkm			/* FALLTHROUGH */
35699357Smarkm		case 't':
35799357Smarkm			add_list(&ttylist, optarg);
35899357Smarkm			xkeep_implied = 1;
35999357Smarkm			nselectors++;
36099357Smarkm			break;
36199357Smarkm		case 'U':
36299357Smarkm			/* This is what SUSv3 defines as the `-u' option. */
363217359Snwhitehorn			add_list(&uidlist, optarg);
36499357Smarkm			xkeep_implied = 1;
36599357Smarkm			nselectors++;
36699357Smarkm			break;
36799357Smarkm		case 'u':
36899357Smarkm			parsefmt(ufmt, 0);
36999357Smarkm			sortby = SORTCPU;
37099357Smarkm			_fmt = 1;
37199357Smarkm			ufmt[0] = '\0';
37299357Smarkm			break;
37399357Smarkm		case 'v':
37499357Smarkm			parsefmt(vfmt, 0);
37599357Smarkm			sortby = SORTMEM;
37699357Smarkm			_fmt = 1;
37799357Smarkm			vfmt[0] = '\0';
37899357Smarkm			break;
37999357Smarkm		case 'w':
38099357Smarkm			if (wflag)
38199357Smarkm				termwidth = UNLIMITED;
38299357Smarkm			else if (termwidth < 131)
38399357Smarkm				termwidth = 131;
38499357Smarkm			wflag++;
38599357Smarkm			break;
38699357Smarkm		case 'X':
38799357Smarkm			/*
38899357Smarkm			 * Note that `-X' and `-x' are not standard "selector"
38999357Smarkm			 * options. For most selector-options, we check *all*
39099357Smarkm			 * processes to see if any are matched by the given
39199357Smarkm			 * value(s).  After we have a set of all the matched
39299357Smarkm			 * processes, then `-X' and `-x' govern whether we
39399357Smarkm			 * modify that *matched* set for processes which do
39499357Smarkm			 * not have a controlling terminal.  `-X' causes
39599357Smarkm			 * those processes to be deleted from the matched
39699357Smarkm			 * set, while `-x' causes them to be kept.
39799357Smarkm			 */
39899357Smarkm			xkeep = 0;
39999357Smarkm			break;
40099357Smarkm		case 'x':
40199357Smarkm			xkeep = 1;
40299357Smarkm			break;
40399357Smarkm		case 'Z':
40499357Smarkm			parsefmt(Zfmt, 0);
40599357Smarkm			Zfmt[0] = '\0';
40699357Smarkm			break;
407167260Skevlo		case '?':
40899357Smarkm		default:
40999357Smarkm			usage();
41099357Smarkm		}
41199357Smarkm	argc -= optind;
41299357Smarkm	argv += optind;
41399357Smarkm
41499357Smarkm	/*
41599357Smarkm	 * If the user specified ps -e then they want a copy of the process
41699357Smarkm	 * environment kvm_getenvv(3) attempts to open /proc/<pid>/mem.
41799357Smarkm	 * Check to make sure that procfs is mounted on /proc, otherwise
41899357Smarkm	 * print a warning informing the user that output will be incomplete.
41999357Smarkm	 */
42099357Smarkm	if (needenv == 1 && check_procfs() == 0)
42199357Smarkm		warnx("Process environment requires procfs(5)");
42299357Smarkm	/*
42399357Smarkm	 * If there arguments after processing all the options, attempt
42499357Smarkm	 * to treat them as a list of process ids.
42599357Smarkm	 */
42699357Smarkm	while (*argv) {
42799357Smarkm		if (!isdigitch(**argv))
42899357Smarkm			break;
42999357Smarkm		add_list(&pidlist, *argv);
43099357Smarkm		argv++;
43199357Smarkm	}
43299357Smarkm	if (*argv) {
43399357Smarkm		fprintf(stderr, "%s: illegal argument: %s\n",
43499357Smarkm		    getprogname(), *argv);
43599357Smarkm		usage();
43699357Smarkm	}
43799357Smarkm	if (optfatal)
43899357Smarkm		exit(1);		/* Error messages already printed. */
43999357Smarkm	if (xkeep < 0)			/* Neither -X nor -x was specified. */
44099357Smarkm		xkeep = xkeep_implied;
44199357Smarkm
44299357Smarkm	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
44399357Smarkm	if (kd == 0)
44499357Smarkm		errx(1, "%s", errbuf);
44599357Smarkm
44699357Smarkm	if (!_fmt)
44799357Smarkm		parsefmt(dfmt, 0);
44899357Smarkm
44999357Smarkm	if (nselectors == 0) {
45099357Smarkm		uidlist.l.ptr = malloc(sizeof(uid_t));
45199357Smarkm		if (uidlist.l.ptr == NULL)
45299357Smarkm			errx(1, "malloc failed");
45399357Smarkm		nselectors = 1;
45499357Smarkm		uidlist.count = uidlist.maxcount = 1;
45599357Smarkm		*uidlist.l.uids = getuid();
45699357Smarkm	}
45799357Smarkm
45899357Smarkm	/*
45999357Smarkm	 * scan requested variables, noting what structures are needed,
46099357Smarkm	 * and adjusting header widths as appropriate.
46199357Smarkm	 */
46299357Smarkm	scanvars();
46399357Smarkm
46499357Smarkm	/*
46599357Smarkm	 * Get process list.  If the user requested just one selector-
46699357Smarkm	 * option, then kvm_getprocs can be asked to return just those
46799357Smarkm	 * processes.  Otherwise, have it return all processes, and
46899357Smarkm	 * then this routine will search that full list and select the
46999357Smarkm	 * processes which match any of the user's selector-options.
47099357Smarkm	 */
47199357Smarkm	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
47299357Smarkm	flag = 0;
47399357Smarkm	if (nselectors == 1) {
47499357Smarkm		if (gidlist.count == 1) {
47599357Smarkm			what = KERN_PROC_RGID | showthreads;
47699357Smarkm			flag = *gidlist.l.gids;
47799357Smarkm			nselectors = 0;
47899357Smarkm		} else if (pgrplist.count == 1) {
47999357Smarkm			what = KERN_PROC_PGRP | showthreads;
48099357Smarkm			flag = *pgrplist.l.pids;
48199357Smarkm			nselectors = 0;
48299357Smarkm		} else if (pidlist.count == 1) {
48399357Smarkm			what = KERN_PROC_PID | showthreads;
48499357Smarkm			flag = *pidlist.l.pids;
48599357Smarkm			nselectors = 0;
48699357Smarkm		} else if (ruidlist.count == 1) {
48799357Smarkm			what = KERN_PROC_RUID | showthreads;
48899357Smarkm			flag = *ruidlist.l.uids;
48999357Smarkm			nselectors = 0;
49099357Smarkm		} else if (sesslist.count == 1) {
49199357Smarkm			what = KERN_PROC_SESSION | showthreads;
49299357Smarkm			flag = *sesslist.l.pids;
49399357Smarkm			nselectors = 0;
49499357Smarkm		} else if (ttylist.count == 1) {
49599357Smarkm			what = KERN_PROC_TTY | showthreads;
49699357Smarkm			flag = *ttylist.l.ttys;
49799357Smarkm			nselectors = 0;
49899357Smarkm		} else if (uidlist.count == 1) {
49999357Smarkm			what = KERN_PROC_UID | showthreads;
50099357Smarkm			flag = *uidlist.l.uids;
50199357Smarkm			nselectors = 0;
50299357Smarkm		} else if (all) {
50399357Smarkm			/* No need for this routine to select processes. */
50499357Smarkm			nselectors = 0;
50599357Smarkm		}
50699357Smarkm	}
50799357Smarkm
50899357Smarkm	/*
50999357Smarkm	 * select procs
51099357Smarkm	 */
51199357Smarkm	nentries = -1;
51299357Smarkm	kp = kvm_getprocs(kd, what, flag, &nentries);
51399357Smarkm	if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
51499357Smarkm		errx(1, "%s", kvm_geterr(kd));
51599357Smarkm	nkept = 0;
51699357Smarkm	if (nentries > 0) {
51799357Smarkm		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
51899357Smarkm			errx(1, "malloc failed");
51999357Smarkm		for (i = nentries; --i >= 0; ++kp) {
52099357Smarkm			/*
52199357Smarkm			 * If the user specified multiple selection-criteria,
52299357Smarkm			 * then keep any process matched by the inclusive OR
52399357Smarkm			 * of all the selection-criteria given.
52499357Smarkm			 */
52599357Smarkm			if (pidlist.count > 0) {
52699357Smarkm				for (elem = 0; elem < pidlist.count; elem++)
52799357Smarkm					if (kp->ki_pid == pidlist.l.pids[elem])
52899357Smarkm						goto keepit;
52999357Smarkm			}
53099357Smarkm			/*
53199357Smarkm			 * Note that we had to process pidlist before
53299357Smarkm			 * filtering out processes which do not have
53399357Smarkm			 * a controlling terminal.
53499357Smarkm			 */
53599357Smarkm			if (xkeep == 0) {
53699357Smarkm				if ((kp->ki_tdev == NODEV ||
53799357Smarkm				    (kp->ki_flag & P_CONTROLT) == 0))
53899357Smarkm					continue;
53999357Smarkm			}
54099357Smarkm			if (nselectors == 0)
54199357Smarkm				goto keepit;
54299357Smarkm			if (gidlist.count > 0) {
54399357Smarkm				for (elem = 0; elem < gidlist.count; elem++)
54499357Smarkm					if (kp->ki_rgid == gidlist.l.gids[elem])
54599357Smarkm						goto keepit;
54699357Smarkm			}
54799357Smarkm			if (pgrplist.count > 0) {
54899357Smarkm				for (elem = 0; elem < pgrplist.count; elem++)
54999357Smarkm					if (kp->ki_pgid ==
55099357Smarkm					    pgrplist.l.pids[elem])
55199357Smarkm						goto keepit;
55299357Smarkm			}
55399357Smarkm			if (ruidlist.count > 0) {
55499357Smarkm				for (elem = 0; elem < ruidlist.count; elem++)
55599357Smarkm					if (kp->ki_ruid ==
55699357Smarkm					    ruidlist.l.uids[elem])
55799357Smarkm						goto keepit;
55899357Smarkm			}
55999357Smarkm			if (sesslist.count > 0) {
56099357Smarkm				for (elem = 0; elem < sesslist.count; elem++)
56199357Smarkm					if (kp->ki_sid == sesslist.l.pids[elem])
56299357Smarkm						goto keepit;
56399357Smarkm			}
56499357Smarkm			if (ttylist.count > 0) {
56599357Smarkm				for (elem = 0; elem < ttylist.count; elem++)
56699357Smarkm					if (kp->ki_tdev == ttylist.l.ttys[elem])
56799357Smarkm						goto keepit;
56899357Smarkm			}
56999357Smarkm			if (uidlist.count > 0) {
57099357Smarkm				for (elem = 0; elem < uidlist.count; elem++)
571228990Suqs					if (kp->ki_uid == uidlist.l.uids[elem])
57299357Smarkm						goto keepit;
57399357Smarkm			}
57499357Smarkm			/*
57599357Smarkm			 * This process did not match any of the user's
57699357Smarkm			 * selector-options, so skip the process.
57799357Smarkm			 */
57899357Smarkm			continue;
57999357Smarkm
58099357Smarkm		keepit:
581283165Semaste			next_KINFO = &kinfo[nkept];
58299357Smarkm			next_KINFO->ki_p = kp;
58399357Smarkm			next_KINFO->ki_d.level = 0;
58499357Smarkm			next_KINFO->ki_d.prefix = NULL;
58599357Smarkm			next_KINFO->ki_pcpu = getpcpu(next_KINFO);
58699357Smarkm			if (sortby == SORTMEM)
58799357Smarkm				next_KINFO->ki_memsize = kp->ki_tsize +
58899357Smarkm				    kp->ki_dsize + kp->ki_ssize;
58999357Smarkm			if (needuser)
59099357Smarkm				saveuser(next_KINFO);
59199357Smarkm			dynsizevars(next_KINFO);
59299357Smarkm			nkept++;
59399357Smarkm		}
59499357Smarkm	}
59599357Smarkm
596147685Sru	sizevars();
59799357Smarkm
59899357Smarkm	/*
59999357Smarkm	 * print header
60099357Smarkm	 */
60199357Smarkm	printheader();
60299357Smarkm	if (nkept == 0)
60399357Smarkm		exit(1);
604147685Sru
605147685Sru	/*
60699357Smarkm	 * sort proc list
60799357Smarkm	 */
60899357Smarkm	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
60999357Smarkm
61099357Smarkm	/*
61199357Smarkm	 * We want things in descendant order
61299357Smarkm	 */
61399357Smarkm	if (descendancy)
61499357Smarkm		descendant_sort(kinfo, nkept);
61599357Smarkm
61699357Smarkm	/*
61799357Smarkm	 * For each process, call each variable output function.
61899357Smarkm	 */
61999357Smarkm	for (i = lineno = 0; i < nkept; i++) {
62099357Smarkm		STAILQ_FOREACH(vent, &varlist, next_ve) {
62199357Smarkm			(vent->var->oproc)(&kinfo[i], vent);
62299357Smarkm			if (STAILQ_NEXT(vent, next_ve) != NULL)
62399357Smarkm				(void)putchar(' ');
62499357Smarkm		}
62599357Smarkm		(void)putchar('\n');
626283165Semaste		if (prtheader && lineno++ == prtheader - 4) {
62799357Smarkm			(void)putchar('\n');
62899357Smarkm			printheader();
62999357Smarkm			lineno = 0;
63099357Smarkm		}
63199357Smarkm	}
63299357Smarkm	free_list(&gidlist);
63399357Smarkm	free_list(&pidlist);
63499357Smarkm	free_list(&pgrplist);
63599357Smarkm	free_list(&ruidlist);
63699357Smarkm	free_list(&sesslist);
63799357Smarkm	free_list(&ttylist);
63899357Smarkm	free_list(&uidlist);
63999357Smarkm	for (i = 0; i < nkept; i++)
64099357Smarkm		free(kinfo[i].ki_d.prefix);
64199357Smarkm	free(kinfo);
64299357Smarkm
64399357Smarkm	exit(eval);
64499357Smarkm}
64599357Smarkm
64699357Smarkmstatic int
64799357Smarkmaddelem_gid(struct listinfo *inf, const char *elem)
64899357Smarkm{
64999357Smarkm	struct group *grp;
65099357Smarkm	const char *nameorID;
65199357Smarkm	char *endp;
65299357Smarkm	u_long bigtemp;
65399357Smarkm
65499357Smarkm	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
65599357Smarkm		if (*elem == '\0')
65699357Smarkm			warnx("Invalid (zero-length) %s name", inf->lname);
65799357Smarkm		else
65899357Smarkm			warnx("%s name too long: %s", inf->lname, elem);
65999357Smarkm		optfatal = 1;
66099357Smarkm		return (0);		/* Do not add this value. */
66199357Smarkm	}
66299357Smarkm
66399357Smarkm	/*
66499357Smarkm	 * SUSv3 states that `ps -G grouplist' should match "real-group
66599357Smarkm	 * ID numbers", and does not mention group-names.  I do want to
66699357Smarkm	 * also support group-names, so this tries for a group-id first,
66799357Smarkm	 * and only tries for a name if that doesn't work.  This is the
66899357Smarkm	 * opposite order of what is done in addelem_uid(), but in
66999357Smarkm	 * practice the order would only matter for group-names which
67099357Smarkm	 * are all-numeric.
67199357Smarkm	 */
67299357Smarkm	grp = NULL;
67399357Smarkm	nameorID = "named";
67499357Smarkm	errno = 0;
67599357Smarkm	bigtemp = strtoul(elem, &endp, 10);
67699357Smarkm	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
67799357Smarkm		nameorID = "name or ID matches";
67899357Smarkm		grp = getgrgid((gid_t)bigtemp);
67999357Smarkm	}
68099357Smarkm	if (grp == NULL)
68199357Smarkm		grp = getgrnam(elem);
68299357Smarkm	if (grp == NULL) {
68399357Smarkm		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
68499357Smarkm		optfatal = 1;
68599357Smarkm		return (0);
68699357Smarkm	}
68799357Smarkm	if (inf->count >= inf->maxcount)
68899357Smarkm		expand_list(inf);
68999357Smarkm	inf->l.gids[(inf->count)++] = grp->gr_gid;
69099357Smarkm	return (1);
69199357Smarkm}
69299357Smarkm
69399357Smarkm#define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h. */
69499357Smarkmstatic int
69599357Smarkmaddelem_pid(struct listinfo *inf, const char *elem)
69699357Smarkm{
69799357Smarkm	char *endp;
69899357Smarkm	long tempid;
69999357Smarkm
70099357Smarkm	if (*elem == '\0') {
70199357Smarkm		warnx("Invalid (zero-length) process id");
70299357Smarkm		optfatal = 1;
70399357Smarkm		return (0);		/* Do not add this value. */
70499357Smarkm	}
70599357Smarkm
70699357Smarkm	errno = 0;
70799357Smarkm	tempid = strtol(elem, &endp, 10);
70899357Smarkm	if (*endp != '\0' || tempid < 0 || elem == endp) {
70999357Smarkm		warnx("Invalid %s: %s", inf->lname, elem);
71099357Smarkm		errno = ERANGE;
71199357Smarkm	} else if (errno != 0 || tempid > BSD_PID_MAX) {
71299357Smarkm		warnx("%s too large: %s", inf->lname, elem);
71399357Smarkm		errno = ERANGE;
71499357Smarkm	}
71599357Smarkm	if (errno == ERANGE) {
71699357Smarkm		optfatal = 1;
71799357Smarkm		return (0);
71899357Smarkm	}
71999357Smarkm	if (inf->count >= inf->maxcount)
72099357Smarkm		expand_list(inf);
72199357Smarkm	inf->l.pids[(inf->count)++] = tempid;
72299357Smarkm	return (1);
72399357Smarkm}
72499357Smarkm#undef	BSD_PID_MAX
72599357Smarkm
72699357Smarkm/*-
72799357Smarkm * The user can specify a device via one of three formats:
72899357Smarkm *     1) fully qualified, e.g.:     /dev/ttyp0 /dev/console	/dev/pts/0
72999357Smarkm *     2) missing "/dev", e.g.:      ttyp0      console		pts/0
73099357Smarkm *     3) two-letters, e.g.:         p0         co		0
73199357Smarkm *        (matching letters that would be seen in the "TT" column)
73299357Smarkm */
73399357Smarkmstatic int
73499357Smarkmaddelem_tty(struct listinfo *inf, const char *elem)
73599357Smarkm{
73699357Smarkm	const char *ttypath;
73799357Smarkm	struct stat sb;
73899357Smarkm	char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
73999357Smarkm
74099357Smarkm	ttypath = NULL;
74199357Smarkm	pathbuf2[0] = '\0';
74299357Smarkm	pathbuf3[0] = '\0';
74399357Smarkm	switch (*elem) {
74499357Smarkm	case '/':
74599357Smarkm		ttypath = elem;
74699357Smarkm		break;
74799357Smarkm	case 'c':
74899357Smarkm		if (strcmp(elem, "co") == 0) {
74999357Smarkm			ttypath = _PATH_CONSOLE;
75099357Smarkm			break;
75199357Smarkm		}
75299357Smarkm		/* FALLTHROUGH */
75399357Smarkm	default:
75499357Smarkm		strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
75599357Smarkm		strlcat(pathbuf, elem, sizeof(pathbuf));
75699357Smarkm		ttypath = pathbuf;
75799357Smarkm		if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
75899357Smarkm			break;
75999357Smarkm		if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
76099357Smarkm			break;
76199357Smarkm		if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
76299357Smarkm			break;
76399357Smarkm		/* Check to see if /dev/tty${elem} exists */
76499357Smarkm		strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
76599357Smarkm		strlcat(pathbuf2, elem, sizeof(pathbuf2));
76699357Smarkm		if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
76799357Smarkm			/* No need to repeat stat() && S_ISCHR() checks */
76899357Smarkm			ttypath = NULL;
76999357Smarkm			break;
77099357Smarkm		}
77199357Smarkm		/* Check to see if /dev/pts/${elem} exists */
77299357Smarkm		strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
77399357Smarkm		strlcat(pathbuf3, elem, sizeof(pathbuf3));
77499357Smarkm		if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
77599357Smarkm			/* No need to repeat stat() && S_ISCHR() checks */
77699357Smarkm			ttypath = NULL;
77799357Smarkm			break;
77899357Smarkm		}
77999357Smarkm		break;
78099357Smarkm	}
78199357Smarkm	if (ttypath) {
78299357Smarkm		if (stat(ttypath, &sb) == -1) {
78399357Smarkm			if (pathbuf3[0] != '\0')
78499357Smarkm				warn("%s, %s, and %s", pathbuf3, pathbuf2,
78599357Smarkm				    ttypath);
78699357Smarkm			else
78799357Smarkm				warn("%s", ttypath);
78899357Smarkm			optfatal = 1;
78999357Smarkm			return (0);
79099357Smarkm		}
79199357Smarkm		if (!S_ISCHR(sb.st_mode)) {
79299357Smarkm			if (pathbuf3[0] != '\0')
79399357Smarkm				warnx("%s, %s, and %s: Not a terminal",
79499357Smarkm				    pathbuf3, pathbuf2, ttypath);
79599357Smarkm			else
79699357Smarkm				warnx("%s: Not a terminal", ttypath);
79799357Smarkm			optfatal = 1;
79899357Smarkm			return (0);
79999357Smarkm		}
80099357Smarkm	}
80199357Smarkm	if (inf->count >= inf->maxcount)
80299357Smarkm		expand_list(inf);
80399357Smarkm	inf->l.ttys[(inf->count)++] = sb.st_rdev;
80499357Smarkm	return (1);
80599357Smarkm}
80699357Smarkm
80799357Smarkmstatic int
80899357Smarkmaddelem_uid(struct listinfo *inf, const char *elem)
80999357Smarkm{
81099357Smarkm	struct passwd *pwd;
81199357Smarkm	char *endp;
81299357Smarkm	u_long bigtemp;
81399357Smarkm
81499357Smarkm	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
81599357Smarkm		if (*elem == '\0')
81699357Smarkm			warnx("Invalid (zero-length) %s name", inf->lname);
81799357Smarkm		else
81899357Smarkm			warnx("%s name too long: %s", inf->lname, elem);
81999357Smarkm		optfatal = 1;
82099357Smarkm		return (0);		/* Do not add this value. */
82199357Smarkm	}
82299357Smarkm
82399357Smarkm	pwd = getpwnam(elem);
82499357Smarkm	if (pwd == NULL) {
82599357Smarkm		errno = 0;
82699357Smarkm		bigtemp = strtoul(elem, &endp, 10);
82799357Smarkm		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
82899357Smarkm			warnx("No %s named '%s'", inf->lname, elem);
82999357Smarkm		else {
83099357Smarkm			/* The string is all digits, so it might be a userID. */
83199357Smarkm			pwd = getpwuid((uid_t)bigtemp);
83299357Smarkm			if (pwd == NULL)
83399357Smarkm				warnx("No %s name or ID matches '%s'",
83499357Smarkm				    inf->lname, elem);
83599357Smarkm		}
83699357Smarkm	}
83799357Smarkm	if (pwd == NULL) {
83899357Smarkm		/*
83999357Smarkm		 * These used to be treated as minor warnings (and the
84099357Smarkm		 * option was simply ignored), but now they are fatal
84199357Smarkm		 * errors (and the command will be aborted).
842293335Semaste		 */
843293335Semaste		optfatal = 1;
844270309Sse		return (0);
845270309Sse	}
846270309Sse	if (inf->count >= inf->maxcount)
847270309Sse		expand_list(inf);
848270309Sse	inf->l.uids[(inf->count)++] = pwd->pw_uid;
84999357Smarkm	return (1);
85099357Smarkm}
85199357Smarkm
85299357Smarkmstatic void
85399357Smarkmadd_list(struct listinfo *inf, const char *argp)
85499357Smarkm{
85599357Smarkm	const char *savep;
85699357Smarkm	char *cp, *endp;
85799357Smarkm	int toolong;
85899357Smarkm	char elemcopy[PATH_MAX];
85999357Smarkm
86099357Smarkm	if (*argp == 0)
86199357Smarkm		inf->addelem(inf, elemcopy);
86299357Smarkm	while (*argp != '\0') {
86399357Smarkm		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
864154151Sflz			argp++;
865154151Sflz		savep = argp;
866154151Sflz		toolong = 0;
86799357Smarkm		cp = elemcopy;
86899357Smarkm		if (strchr(T_SEP, *argp) == NULL) {
86999357Smarkm			endp = elemcopy + sizeof(elemcopy) - 1;
87099357Smarkm			while (*argp != '\0' && cp <= endp &&
87199357Smarkm			    strchr(W_SEP T_SEP, *argp) == NULL)
872				*cp++ = *argp++;
873			if (cp > endp)
874				toolong = 1;
875		}
876		if (!toolong) {
877			*cp = '\0';
878			/*
879			 * Add this single element to the given list.
880			 */
881			inf->addelem(inf, elemcopy);
882		} else {
883			/*
884			 * The string is too long to copy.  Find the end
885			 * of the string to print out the warning message.
886			 */
887			while (*argp != '\0' && strchr(W_SEP T_SEP,
888			    *argp) == NULL)
889				argp++;
890			warnx("Value too long: %.*s", (int)(argp - savep),
891			    savep);
892			optfatal = 1;
893		}
894		/*
895		 * Skip over any number of trailing whitespace characters,
896		 * but only one (at most) trailing element-terminating
897		 * character.
898		 */
899		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
900			argp++;
901		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
902			argp++;
903			/* Catch case where string ended with a comma. */
904			if (*argp == '\0')
905				inf->addelem(inf, argp);
906		}
907	}
908}
909
910static void
911descendant_sort(KINFO *ki, int items)
912{
913	int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
914	unsigned char *path;
915	KINFO kn;
916
917	/*
918	 * First, sort the entries by descendancy, tracking the descendancy
919	 * depth in the ki_d.level field.
920	 */
921	src = 0;
922	maxlvl = 0;
923	while (src < items) {
924		if (ki[src].ki_d.level) {
925			src++;
926			continue;
927		}
928		for (nsrc = 1; src + nsrc < items; nsrc++)
929			if (!ki[src + nsrc].ki_d.level)
930				break;
931
932		for (dst = 0; dst < items; dst++) {
933			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
934				continue;
935			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
936				break;
937		}
938
939		if (dst == items) {
940			src += nsrc;
941			continue;
942		}
943
944		for (ndst = 1; dst + ndst < items; ndst++)
945			if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
946				break;
947
948		for (n = src; n < src + nsrc; n++) {
949			ki[n].ki_d.level += ki[dst].ki_d.level + 1;
950			if (maxlvl < ki[n].ki_d.level)
951				maxlvl = ki[n].ki_d.level;
952		}
953
954		while (nsrc) {
955			if (src < dst) {
956				kn = ki[src];
957				memmove(ki + src, ki + src + 1,
958				    (dst - src + ndst - 1) * sizeof *ki);
959				ki[dst + ndst - 1] = kn;
960				nsrc--;
961				dst--;
962				ndst++;
963			} else if (src != dst + ndst) {
964				kn = ki[src];
965				memmove(ki + dst + ndst + 1, ki + dst + ndst,
966				    (src - dst - ndst) * sizeof *ki);
967				ki[dst + ndst] = kn;
968				ndst++;
969				nsrc--;
970				src++;
971			} else {
972				ndst += nsrc;
973				src += nsrc;
974				nsrc = 0;
975			}
976		}
977	}
978
979	/*
980	 * Now populate ki_d.prefix (instead of ki_d.level) with the command
981	 * prefix used to show descendancies.
982	 */
983	path = malloc((maxlvl + 7) / 8);
984	memset(path, '\0', (maxlvl + 7) / 8);
985	for (src = 0; src < items; src++) {
986		if ((lvl = ki[src].ki_d.level) == 0) {
987			ki[src].ki_d.prefix = NULL;
988			continue;
989		}
990		if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
991			errx(1, "malloc failed");
992		for (n = 0; n < lvl - 2; n++) {
993			ki[src].ki_d.prefix[n * 2] =
994			    path[n / 8] & 1 << (n % 8) ? '|' : ' ';
995			ki[src].ki_d.prefix[n * 2 + 1] = ' ';
996		}
997		if (n == lvl - 2) {
998			/* Have I any more siblings? */
999			for (siblings = 0, dst = src + 1; dst < items; dst++) {
1000				if (ki[dst].ki_d.level > lvl)
1001					continue;
1002				if (ki[dst].ki_d.level == lvl)
1003					siblings = 1;
1004				break;
1005			}
1006			if (siblings)
1007				path[n / 8] |= 1 << (n % 8);
1008			else
1009				path[n / 8] &= ~(1 << (n % 8));
1010			ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1011			ki[src].ki_d.prefix[n * 2 + 1] = '-';
1012			n++;
1013		}
1014		strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1015	}
1016	free(path);
1017}
1018
1019static void *
1020expand_list(struct listinfo *inf)
1021{
1022	void *newlist;
1023	int newmax;
1024
1025	newmax = (inf->maxcount + 1) << 1;
1026	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1027	if (newlist == NULL) {
1028		free(inf->l.ptr);
1029		errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1030	}
1031	inf->maxcount = newmax;
1032	inf->l.ptr = newlist;
1033
1034	return (newlist);
1035}
1036
1037static void
1038free_list(struct listinfo *inf)
1039{
1040
1041	inf->count = inf->elemsize = inf->maxcount = 0;
1042	if (inf->l.ptr != NULL)
1043		free(inf->l.ptr);
1044	inf->addelem = NULL;
1045	inf->lname = NULL;
1046	inf->l.ptr = NULL;
1047}
1048
1049static void
1050init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1051    const char *lname)
1052{
1053
1054	inf->count = inf->maxcount = 0;
1055	inf->elemsize = elemsize;
1056	inf->addelem = artn;
1057	inf->lname = lname;
1058	inf->l.ptr = NULL;
1059}
1060
1061VARENT *
1062find_varentry(VAR *v)
1063{
1064	struct varent *vent;
1065
1066	STAILQ_FOREACH(vent, &varlist, next_ve) {
1067		if (strcmp(vent->var->name, v->name) == 0)
1068			return vent;
1069	}
1070	return NULL;
1071}
1072
1073static void
1074scanvars(void)
1075{
1076	struct varent *vent;
1077	VAR *v;
1078
1079	STAILQ_FOREACH(vent, &varlist, next_ve) {
1080		v = vent->var;
1081		if (v->flag & DSIZ) {
1082			v->dwidth = v->width;
1083			v->width = 0;
1084		}
1085		if (v->flag & USER)
1086			needuser = 1;
1087		if (v->flag & COMM)
1088			needcomm = 1;
1089	}
1090}
1091
1092static void
1093dynsizevars(KINFO *ki)
1094{
1095	struct varent *vent;
1096	VAR *v;
1097	int i;
1098
1099	STAILQ_FOREACH(vent, &varlist, next_ve) {
1100		v = vent->var;
1101		if (!(v->flag & DSIZ))
1102			continue;
1103		i = (v->sproc)( ki);
1104		if (v->width < i)
1105			v->width = i;
1106		if (v->width > v->dwidth)
1107			v->width = v->dwidth;
1108	}
1109}
1110
1111static void
1112sizevars(void)
1113{
1114	struct varent *vent;
1115	VAR *v;
1116	int i;
1117
1118	STAILQ_FOREACH(vent, &varlist, next_ve) {
1119		v = vent->var;
1120		i = strlen(vent->header);
1121		if (v->width < i)
1122			v->width = i;
1123		totwidth += v->width + 1;	/* +1 for space */
1124	}
1125	totwidth--;
1126}
1127
1128static const char *
1129fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
1130    char *comm, int maxlen)
1131{
1132	const char *s;
1133
1134	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
1135	return (s);
1136}
1137
1138#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_flag & P_INMEM))
1139
1140static void
1141saveuser(KINFO *ki)
1142{
1143
1144	if (ki->ki_p->ki_flag & P_INMEM) {
1145		/*
1146		 * The u-area might be swapped out, and we can't get
1147		 * at it because we have a crashdump and no swap.
1148		 * If it's here fill in these fields, otherwise, just
1149		 * leave them 0.
1150		 */
1151		ki->ki_valid = 1;
1152	} else
1153		ki->ki_valid = 0;
1154	/*
1155	 * save arguments if needed
1156	 */
1157	if (needcomm) {
1158		if (ki->ki_p->ki_stat == SZOMB)
1159			ki->ki_args = strdup("<defunct>");
1160		else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
1161			ki->ki_args = strdup(fmt(kvm_getargv, ki,
1162			    ki->ki_p->ki_comm, MAXCOMLEN));
1163		else
1164			asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
1165		if (ki->ki_args == NULL)
1166			errx(1, "malloc failed");
1167	} else {
1168		ki->ki_args = NULL;
1169	}
1170	if (needenv) {
1171		if (UREADOK(ki))
1172			ki->ki_env = strdup(fmt(kvm_getenvv, ki,
1173			    (char *)NULL, 0));
1174		else
1175			ki->ki_env = strdup("()");
1176		if (ki->ki_env == NULL)
1177			errx(1, "malloc failed");
1178	} else {
1179		ki->ki_env = NULL;
1180	}
1181}
1182
1183/* A macro used to improve the readability of pscomp(). */
1184#define	DIFF_RETURN(a, b, field) do {	\
1185	if ((a)->field != (b)->field)	\
1186		return (((a)->field < (b)->field) ? -1 : 1); 	\
1187} while (0)
1188
1189static int
1190pscomp(const void *a, const void *b)
1191{
1192	const KINFO *ka, *kb;
1193
1194	ka = a;
1195	kb = b;
1196	/* SORTCPU and SORTMEM are sorted in descending order. */
1197	if (sortby == SORTCPU)
1198		DIFF_RETURN(kb, ka, ki_pcpu);
1199	if (sortby == SORTMEM)
1200		DIFF_RETURN(kb, ka, ki_memsize);
1201	/*
1202	 * TTY's are sorted in ascending order, except that all NODEV
1203	 * processes come before all processes with a device.
1204	 */
1205	if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1206		if (ka->ki_p->ki_tdev == NODEV)
1207			return (-1);
1208		if (kb->ki_p->ki_tdev == NODEV)
1209			return (1);
1210		DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1211	}
1212
1213	/* PID's and TID's (threads) are sorted in ascending order. */
1214	DIFF_RETURN(ka, kb, ki_p->ki_pid);
1215	DIFF_RETURN(ka, kb, ki_p->ki_tid);
1216	return (0);
1217}
1218#undef DIFF_RETURN
1219
1220/*
1221 * ICK (all for getopt), would rather hide the ugliness
1222 * here than taint the main code.
1223 *
1224 *  ps foo -> ps -foo
1225 *  ps 34 -> ps -p34
1226 *
1227 * The old convention that 't' with no trailing tty arg means the users
1228 * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1229 * feature is available with the option 'T', which takes no argument.
1230 */
1231static char *
1232kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1233{
1234	size_t len;
1235	char *argp, *cp, *newopts, *ns, *optp, *pidp;
1236
1237	/*
1238	 * See if the original value includes any option which takes an
1239	 * argument (and will thus use up the remainder of the string).
1240	 */
1241	argp = NULL;
1242	if (optlist != NULL) {
1243		for (cp = origval; *cp != '\0'; cp++) {
1244			optp = strchr(optlist, *cp);
1245			if ((optp != NULL) && *(optp + 1) == ':') {
1246				argp = cp;
1247				break;
1248			}
1249		}
1250	}
1251	if (argp != NULL && *origval == '-')
1252		return (origval);
1253
1254	/*
1255	 * if last letter is a 't' flag with no argument (in the context
1256	 * of the oldps options -- option string NOT starting with a '-' --
1257	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1258	 *
1259	 * However, if a flag accepting a string argument is found earlier
1260	 * in the option string (including a possible `t' flag), then the
1261	 * remainder of the string must be the argument to that flag; so
1262	 * do not modify that argument.  Note that a trailing `t' would
1263	 * cause argp to be set, if argp was not already set by some
1264	 * earlier option.
1265	 */
1266	len = strlen(origval);
1267	cp = origval + len - 1;
1268	pidp = NULL;
1269	if (*cp == 't' && *origval != '-' && cp == argp) {
1270		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1271			*cp = 'T';
1272	} else if (argp == NULL) {
1273		/*
1274		 * The original value did not include any option which takes
1275		 * an argument (and that would include `p' and `t'), so check
1276		 * the value for trailing number, or comma-separated list of
1277		 * numbers, which we will treat as a pid request.
1278		 */
1279		if (isdigitch(*cp)) {
1280			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1281				--cp;
1282			pidp = cp + 1;
1283		}
1284	}
1285
1286	/*
1287	 * If nothing needs to be added to the string, then return
1288	 * the "original" (although possibly modified) value.
1289	 */
1290	if (*origval == '-' && pidp == NULL)
1291		return (origval);
1292
1293	/*
1294	 * Create a copy of the string to add '-' and/or 'p' to the
1295	 * original value.
1296	 */
1297	if ((newopts = ns = malloc(len + 3)) == NULL)
1298		errx(1, "malloc failed");
1299
1300	if (*origval != '-')
1301		*ns++ = '-';	/* add option flag */
1302
1303	if (pidp == NULL)
1304		strcpy(ns, origval);
1305	else {
1306		/*
1307		 * Copy everything before the pid string, add the `p',
1308		 * and then copy the pid string.
1309		 */
1310		len = pidp - origval;
1311		memcpy(ns, origval, len);
1312		ns += len;
1313		*ns++ = 'p';
1314		strcpy(ns, pidp);
1315	}
1316
1317	return (newopts);
1318}
1319
1320static int
1321check_procfs(void)
1322{
1323	struct statfs mnt;
1324
1325	if (statfs("/proc", &mnt) < 0)
1326		return (0);
1327	if (strcmp(mnt.f_fstypename, "procfs") != 0)
1328		return (0);
1329	return (1);
1330}
1331
1332static void
1333usage(void)
1334{
1335#define	SINGLE_OPTS	"[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1336
1337	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1338	    "usage: ps " SINGLE_OPTS " [-O fmt | -o fmt] [-G gid[,gid...]]",
1339	    "          [-M core] [-N system]",
1340	    "          [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",
1341	    "       ps [-L]");
1342	exit(1);
1343}
1344