xref: /freebsd/bin/ps/ps.c (revision 092e2ff33be2fbe878ad65fe2e9daea918e35e39)
14b88c807SRodney W. Grimes /*-
28a16b7a1SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
38a16b7a1SPedro F. Giffuni  *
44b88c807SRodney W. Grimes  * Copyright (c) 1990, 1993, 1994
54b88c807SRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
64b88c807SRodney W. Grimes  *
74b88c807SRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
84b88c807SRodney W. Grimes  * modification, are permitted provided that the following conditions
94b88c807SRodney W. Grimes  * are met:
104b88c807SRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
114b88c807SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
124b88c807SRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
134b88c807SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
144b88c807SRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
15fbbd9655SWarner Losh  * 3. Neither the name of the University nor the names of its contributors
164b88c807SRodney W. Grimes  *    may be used to endorse or promote products derived from this software
174b88c807SRodney W. Grimes  *    without specific prior written permission.
184b88c807SRodney W. Grimes  *
194b88c807SRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
204b88c807SRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
214b88c807SRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
224b88c807SRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
234b88c807SRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
244b88c807SRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
254b88c807SRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
264b88c807SRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
274b88c807SRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
284b88c807SRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
294b88c807SRodney W. Grimes  * SUCH DAMAGE.
30a4c8a745SGarance A Drosehn  * ------+---------+---------+-------- + --------+---------+---------+---------*
31a4c8a745SGarance A Drosehn  * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
32a4c8a745SGarance A Drosehn  * All rights reserved.
33a4c8a745SGarance A Drosehn  *
34a4c8a745SGarance A Drosehn  * Significant modifications made to bring `ps' options somewhat closer
35a4c8a745SGarance A Drosehn  * to the standard for `ps' as described in SingleUnixSpec-v3.
36a4c8a745SGarance A Drosehn  * ------+---------+---------+-------- + --------+---------+---------+---------*
374b88c807SRodney W. Grimes  */
384b88c807SRodney W. Grimes 
394b88c807SRodney W. Grimes #include <sys/param.h>
4013767130SBryan Drewery #include <sys/jail.h>
41c7910c3aSGarance A Drosehn #include <sys/proc.h>
428b6f5f5fSDavid Greenman #include <sys/user.h>
434b88c807SRodney W. Grimes #include <sys/stat.h>
444b88c807SRodney W. Grimes #include <sys/ioctl.h>
454b88c807SRodney W. Grimes #include <sys/sysctl.h>
46a951d1f8SChristian S.J. Peron #include <sys/mount.h>
474b88c807SRodney W. Grimes 
484b88c807SRodney W. Grimes #include <ctype.h>
494e8b6a6fSGarance A Drosehn #include <errno.h>
504b88c807SRodney W. Grimes #include <fcntl.h>
51a4c8a745SGarance A Drosehn #include <grp.h>
5213767130SBryan Drewery #include <jail.h>
534b88c807SRodney W. Grimes #include <kvm.h>
54b2496d93SMike Pritchard #include <limits.h>
5508017519SAndrey A. Chernov #include <locale.h>
564b88c807SRodney W. Grimes #include <paths.h>
57871e8d8cSMark Murray #include <pwd.h>
584b88c807SRodney W. Grimes #include <stdio.h>
594b88c807SRodney W. Grimes #include <stdlib.h>
604b88c807SRodney W. Grimes #include <string.h>
614b88c807SRodney W. Grimes #include <unistd.h>
628beb1a2fSMarcel Moolenaar #include <libxo/xo.h>
634b88c807SRodney W. Grimes 
644b88c807SRodney W. Grimes #include "ps.h"
654b88c807SRodney W. Grimes 
668a529f59SJohn Baldwin #define	_PATH_PTS	"/dev/pts/"
678a529f59SJohn Baldwin 
68a4c8a745SGarance A Drosehn #define	W_SEP	" \t"		/* "Whitespace" list separators */
69a4c8a745SGarance A Drosehn #define	T_SEP	","		/* "Terminate-element" list separators */
70cf22dcfcSBrian Somers 
71c675340aSGarance A Drosehn /*
72ecbb06f8SGarance A Drosehn  * isdigit takes an `int', but expects values in the range of unsigned char.
73ecbb06f8SGarance A Drosehn  * This wrapper ensures that values from a 'char' end up in the correct range.
74c675340aSGarance A Drosehn  */
75ecbb06f8SGarance A Drosehn #define	isdigitch(Anychar) isdigit((u_char)(Anychar))
76c675340aSGarance A Drosehn 
77db91faacSPeter Wemm int	 cflag;			/* -c */
78de800cd4SGarance A Drosehn int	 eval;			/* Exit value */
79de800cd4SGarance A Drosehn time_t	 now;			/* Current time(3) value */
804b88c807SRodney W. Grimes int	 rawcpu;		/* -C */
814b88c807SRodney W. Grimes int	 sumrusage;		/* -S */
82de800cd4SGarance A Drosehn int	 termwidth;		/* Width of the screen (0 == infinity). */
837ab24ea3SJulian Elischer int	 showthreads;		/* will threads be shown? */
844b88c807SRodney W. Grimes 
85bdf8ab46SGarance A Drosehn struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
86de800cd4SGarance A Drosehn 
87de800cd4SGarance A Drosehn static kvm_t	*kd;
88de800cd4SGarance A Drosehn static int	 needcomm;	/* -o "command" */
89de800cd4SGarance A Drosehn static int	 needenv;	/* -e */
90de800cd4SGarance A Drosehn static int	 needuser;	/* -o "user" */
91de800cd4SGarance A Drosehn static int	 optfatal;	/* Fatal error parsing some list-option. */
921818f3fdSBrooks Davis static int	 pid_max;	/* kern.pid_max */
93de800cd4SGarance A Drosehn 
94de800cd4SGarance A Drosehn static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
95ba2cd770SJuli Mallett 
96a4c8a745SGarance A Drosehn struct listinfo;
97de800cd4SGarance A Drosehn typedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
98a4c8a745SGarance A Drosehn 
99a4c8a745SGarance A Drosehn struct listinfo {
100a4c8a745SGarance A Drosehn 	int		 count;
101a4c8a745SGarance A Drosehn 	int		 maxcount;
102a4c8a745SGarance A Drosehn 	int		 elemsize;
103a4c8a745SGarance A Drosehn 	addelem_rtn	*addelem;
104a4c8a745SGarance A Drosehn 	const char	*lname;
105a4c8a745SGarance A Drosehn 	union {
106a4c8a745SGarance A Drosehn 		gid_t	*gids;
10713767130SBryan Drewery 		int	*jids;
108a4c8a745SGarance A Drosehn 		pid_t	*pids;
109a4c8a745SGarance A Drosehn 		dev_t	*ttys;
110a4c8a745SGarance A Drosehn 		uid_t	*uids;
111a4c8a745SGarance A Drosehn 		void	*ptr;
112d822163fSGarance A Drosehn 	} l;
113a4c8a745SGarance A Drosehn };
114a4c8a745SGarance A Drosehn 
115a4c8a745SGarance A Drosehn static int	 addelem_gid(struct listinfo *, const char *);
11613767130SBryan Drewery static int	 addelem_jid(struct listinfo *, const char *);
117a4c8a745SGarance A Drosehn static int	 addelem_pid(struct listinfo *, const char *);
118a4c8a745SGarance A Drosehn static int	 addelem_tty(struct listinfo *, const char *);
119a4c8a745SGarance A Drosehn static int	 addelem_uid(struct listinfo *, const char *);
120a4c8a745SGarance A Drosehn static void	 add_list(struct listinfo *, const char *);
121044fce53SBrian Somers static void	 descendant_sort(KINFO *, int);
1221d1143ecSEdward Tomasz Napierala static void	 format_output(KINFO *);
123a4c8a745SGarance A Drosehn static void	*expand_list(struct listinfo *);
124f35e0715SGarance A Drosehn static const char *
125f35e0715SGarance A Drosehn 		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
1261c67ef12SJohn Baldwin 		    KINFO *, char *, char *, int);
127a4c8a745SGarance A Drosehn static void	 free_list(struct listinfo *);
128a4c8a745SGarance A Drosehn static void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
12925113083SGarance A Drosehn static char	*kludge_oldps_options(const char *, char *, const char *);
1304857f240SGarance A Drosehn static int	 pscomp(const void *, const void *);
1314857f240SGarance A Drosehn static void	 saveuser(KINFO *);
1324857f240SGarance A Drosehn static void	 scanvars(void);
1334857f240SGarance A Drosehn static void	 sizevars(void);
13464b0bf0bSPawel Jakub Dawidek static void	 pidmax_init(void);
1354857f240SGarance A Drosehn static void	 usage(void);
1364b88c807SRodney W. Grimes 
137c0716492SJuli Mallett static char dfmt[] = "pid,tt,state,time,command";
138259fcfacSGarance A Drosehn static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
1391d2324f4SGarance A Drosehn static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
1401d2324f4SGarance A Drosehn 			"tt,time,command";
141871e8d8cSMark Murray static char   o1[] = "pid";
142c0716492SJuli Mallett static char   o2[] = "tt,state,time,command";
143c0716492SJuli Mallett static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
1441d2324f4SGarance A Drosehn static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
1451d2324f4SGarance A Drosehn 			"%cpu,%mem,command";
1462af538ebSRobert Watson static char Zfmt[] = "label";
1474b88c807SRodney W. Grimes 
14862e6ca0fSKonstantin Belousov #define	PS_ARGS	"AaCcD:defG:gHhjJ:LlM:mN:O:o:p:rSTt:U:uvwXxZ"
14941623b2dSMaxim Sobolev 
1504b88c807SRodney W. Grimes int
main(int argc,char * argv[])15146251ddeSWarner Losh main(int argc, char *argv[])
1524b88c807SRodney W. Grimes {
15313767130SBryan Drewery 	struct listinfo gidlist, jidlist, pgrplist, pidlist;
154a4c8a745SGarance A Drosehn 	struct listinfo ruidlist, sesslist, ttylist, uidlist;
1554b88c807SRodney W. Grimes 	struct kinfo_proc *kp;
1561d1143ecSEdward Tomasz Napierala 	KINFO *kinfo = NULL, *next_KINFO;
1571d1143ecSEdward Tomasz Napierala 	KINFO_STR *ks;
1584b88c807SRodney W. Grimes 	struct varent *vent;
159484f5781SPedro F. Giffuni 	struct winsize ws = { .ws_row = 0 };
16016eb3576SMarcelo Araujo 	const char *nlistf, *memf, *str;
161ca62e195SGarance A Drosehn 	char *cols;
1621d1143ecSEdward Tomasz Napierala 	int all, ch, elem, flag, _fmt, i, lineno, linelen, left;
163044fce53SBrian Somers 	int descendancy, nentries, nkept, nselectors;
1647ab24ea3SJulian Elischer 	int prtheader, wflag, what, xkeep, xkeep_implied;
1658beb1a2fSMarcel Moolenaar 	int fwidthmin, fwidthmax;
166871e8d8cSMark Murray 	char errbuf[_POSIX2_LINE_MAX];
1678beb1a2fSMarcel Moolenaar 	char fmtbuf[_POSIX2_LINE_MAX];
1685c0a1c15SPiotr Pawel Stefaniak 	enum { NONE = 0, UP = 1, DOWN = 2, BOTH = 1 | 2 } directions = NONE;
1695c0a1c15SPiotr Pawel Stefaniak 	struct { int traversed; int initial; } pid_count;
1704b88c807SRodney W. Grimes 
1712bf4b9cfSAndrey A. Chernov 	(void) setlocale(LC_ALL, "");
172352b6523SGarance A Drosehn 	time(&now);			/* Used by routines in print.c. */
1732bf4b9cfSAndrey A. Chernov 
174b93bb974SMike Karels 	/*
175b93bb974SMike Karels 	 * Compute default output line length before processing options.
176b93bb974SMike Karels 	 * If COLUMNS is set, use it.  Otherwise, if this is part of an
177b93bb974SMike Karels 	 * interactive job (i.e. one associated with a terminal), use
178b93bb974SMike Karels 	 * the terminal width.  "Interactive" is determined by whether
179b93bb974SMike Karels 	 * any of stdout, stderr, or stdin is a terminal.  The intent
180b93bb974SMike Karels 	 * is that "ps", "ps | more", and "ps | grep" all use the same
181b93bb974SMike Karels 	 * default line length unless -w is specified.
18230417f2cSMike Karels 	 *
18330417f2cSMike Karels 	 * If not interactive, the default length was traditionally 79.
18430417f2cSMike Karels 	 * It has been changed to unlimited.  This is mostly for the
18530417f2cSMike Karels 	 * benefit of non-interactive scripts, which arguably should
18630417f2cSMike Karels 	 * use -ww, but is compatible with Linux.
187b93bb974SMike Karels 	 */
1884f18100dSTim J. Robbins 	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
1894f18100dSTim J. Robbins 		termwidth = atoi(cols);
1904f18100dSTim J. Robbins 	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1914b88c807SRodney W. Grimes 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1924b88c807SRodney W. Grimes 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
1934b88c807SRodney W. Grimes 	     ws.ws_col == 0)
19430417f2cSMike Karels 		termwidth = UNLIMITED;
1954b88c807SRodney W. Grimes 	else
1964b88c807SRodney W. Grimes 		termwidth = ws.ws_col - 1;
1974b88c807SRodney W. Grimes 
19841623b2dSMaxim Sobolev 	/*
199c675340aSGarance A Drosehn 	 * Hide a number of option-processing kludges in a separate routine,
200c675340aSGarance A Drosehn 	 * to support some historical BSD behaviors, such as `ps axu'.
20141623b2dSMaxim Sobolev 	 */
202c675340aSGarance A Drosehn 	if (argc > 1)
203bf46a3bfSGarance A Drosehn 		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
2044b88c807SRodney W. Grimes 
20564b0bf0bSPawel Jakub Dawidek 	pidmax_init();
20664b0bf0bSPawel Jakub Dawidek 
207044fce53SBrian Somers 	all = descendancy = _fmt = nselectors = optfatal = 0;
208352b6523SGarance A Drosehn 	prtheader = showthreads = wflag = xkeep_implied = 0;
209352b6523SGarance A Drosehn 	xkeep = -1;			/* Neither -x nor -X. */
210a4c8a745SGarance A Drosehn 	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
21113767130SBryan Drewery 	init_list(&jidlist, addelem_jid, sizeof(int), "jail id");
212a4c8a745SGarance A Drosehn 	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
213a4c8a745SGarance A Drosehn 	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
214a4c8a745SGarance A Drosehn 	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
215a4c8a745SGarance A Drosehn 	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
216a4c8a745SGarance A Drosehn 	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
217a4c8a745SGarance A Drosehn 	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
218c08dcaf1SRebecca Cran 	memf = _PATH_DEVNULL;
219c08dcaf1SRebecca Cran 	nlistf = NULL;
2208beb1a2fSMarcel Moolenaar 
2218beb1a2fSMarcel Moolenaar 	argc = xo_parse_args(argc, argv);
2228beb1a2fSMarcel Moolenaar 	if (argc < 0)
2238beb1a2fSMarcel Moolenaar 		exit(1);
2248beb1a2fSMarcel Moolenaar 
22541623b2dSMaxim Sobolev 	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
2260c025af9SKevin Lo 		switch (ch) {
227a4c8a745SGarance A Drosehn 		case 'A':
228a4c8a745SGarance A Drosehn 			/*
229a4c8a745SGarance A Drosehn 			 * Exactly the same as `-ax'.   This has been
230bf2fe08eSUlrich Spörlein 			 * added for compatibility with SUSv3, but for
231a4c8a745SGarance A Drosehn 			 * now it will not be described in the man page.
232a4c8a745SGarance A Drosehn 			 */
233a4c8a745SGarance A Drosehn 			all = xkeep = 1;
234a4c8a745SGarance A Drosehn 			break;
2354b88c807SRodney W. Grimes 		case 'a':
2364b88c807SRodney W. Grimes 			all = 1;
2374b88c807SRodney W. Grimes 			break;
2384b88c807SRodney W. Grimes 		case 'C':
2394b88c807SRodney W. Grimes 			rawcpu = 1;
2404b88c807SRodney W. Grimes 			break;
241db91faacSPeter Wemm 		case 'c':
242db91faacSPeter Wemm 			cflag = 1;
243db91faacSPeter Wemm 			break;
2445c0a1c15SPiotr Pawel Stefaniak 		case 'D': {
2455c0a1c15SPiotr Pawel Stefaniak 				size_t len = strlen(optarg);
2465c0a1c15SPiotr Pawel Stefaniak 
2475c0a1c15SPiotr Pawel Stefaniak 				if (len <= 2 &&
2485c0a1c15SPiotr Pawel Stefaniak 					strncasecmp(optarg, "up", len) == 0)
2495c0a1c15SPiotr Pawel Stefaniak 					directions |= UP;
2505c0a1c15SPiotr Pawel Stefaniak 				else if (len <= 4 &&
2515c0a1c15SPiotr Pawel Stefaniak 					strncasecmp(optarg, "down", len) == 0)
2525c0a1c15SPiotr Pawel Stefaniak 					directions |= DOWN;
2535c0a1c15SPiotr Pawel Stefaniak 				else if (len <= 4 &&
2545c0a1c15SPiotr Pawel Stefaniak 					strncasecmp(optarg, "both", len) == 0)
2555c0a1c15SPiotr Pawel Stefaniak 					directions |= BOTH;
2563f0b80bcSJamie Landeg-Jones 				else
2573f0b80bcSJamie Landeg-Jones 					usage();
2585c0a1c15SPiotr Pawel Stefaniak 				break;
2595c0a1c15SPiotr Pawel Stefaniak 			}
260044fce53SBrian Somers 		case 'd':
261044fce53SBrian Somers 			descendancy = 1;
262044fce53SBrian Somers 			break;
263db91faacSPeter Wemm 		case 'e':			/* XXX set ufmt */
264db91faacSPeter Wemm 			needenv = 1;
265db91faacSPeter Wemm 			break;
2664a355d17SGarance A Drosehn 		case 'f':
26762e6ca0fSKonstantin Belousov 			/* compat */
2684a355d17SGarance A Drosehn 			break;
269a4c8a745SGarance A Drosehn 		case 'G':
270a4c8a745SGarance A Drosehn 			add_list(&gidlist, optarg);
271a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
272a4c8a745SGarance A Drosehn 			nselectors++;
273a4c8a745SGarance A Drosehn 			break;
2744b88c807SRodney W. Grimes 		case 'g':
275352b6523SGarance A Drosehn #if 0
276ba50b0e0SGarance A Drosehn 			/*-
277352b6523SGarance A Drosehn 			 * XXX - This SUSv3 behavior is still under debate
278352b6523SGarance A Drosehn 			 *	since it conflicts with the (undocumented)
279352b6523SGarance A Drosehn 			 *	`-g' option.  So we skip it for now.
280352b6523SGarance A Drosehn 			 */
281a4c8a745SGarance A Drosehn 			add_list(&pgrplist, optarg);
282a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
283a4c8a745SGarance A Drosehn 			nselectors++;
284a4c8a745SGarance A Drosehn 			break;
285a4c8a745SGarance A Drosehn #else
286352b6523SGarance A Drosehn 			/* The historical BSD-ish (from SunOS) behavior. */
2874b88c807SRodney W. Grimes 			break;			/* no-op */
288a4c8a745SGarance A Drosehn #endif
28948b8c0deSScott Long 		case 'H':
290d75c1d83SDaniel Eischen 			showthreads = KERN_PROC_INC_THREAD;
29148b8c0deSScott Long 			break;
2924b88c807SRodney W. Grimes 		case 'h':
2934b88c807SRodney W. Grimes 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
2944b88c807SRodney W. Grimes 			break;
29513767130SBryan Drewery 		case 'J':
29613767130SBryan Drewery 			add_list(&jidlist, optarg);
29713767130SBryan Drewery 			xkeep_implied = 1;
29813767130SBryan Drewery 			nselectors++;
29913767130SBryan Drewery 			break;
3004b88c807SRodney W. Grimes 		case 'j':
301fde411d5SJuli Mallett 			parsefmt(jfmt, 0);
302871e8d8cSMark Murray 			_fmt = 1;
3034b88c807SRodney W. Grimes 			jfmt[0] = '\0';
3044b88c807SRodney W. Grimes 			break;
3054b88c807SRodney W. Grimes 		case 'L':
3064b88c807SRodney W. Grimes 			showkey();
3074b88c807SRodney W. Grimes 			exit(0);
3084b88c807SRodney W. Grimes 		case 'l':
309fde411d5SJuli Mallett 			parsefmt(lfmt, 0);
310871e8d8cSMark Murray 			_fmt = 1;
3114b88c807SRodney W. Grimes 			lfmt[0] = '\0';
3124b88c807SRodney W. Grimes 			break;
3134b88c807SRodney W. Grimes 		case 'M':
3144b88c807SRodney W. Grimes 			memf = optarg;
3154b88c807SRodney W. Grimes 			break;
3164b88c807SRodney W. Grimes 		case 'm':
3174b88c807SRodney W. Grimes 			sortby = SORTMEM;
3184b88c807SRodney W. Grimes 			break;
3194b88c807SRodney W. Grimes 		case 'N':
3204b88c807SRodney W. Grimes 			nlistf = optarg;
3214b88c807SRodney W. Grimes 			break;
3224b88c807SRodney W. Grimes 		case 'O':
323fde411d5SJuli Mallett 			parsefmt(o1, 1);
324fde411d5SJuli Mallett 			parsefmt(optarg, 1);
325fde411d5SJuli Mallett 			parsefmt(o2, 1);
3264b88c807SRodney W. Grimes 			o1[0] = o2[0] = '\0';
327871e8d8cSMark Murray 			_fmt = 1;
3284b88c807SRodney W. Grimes 			break;
3294b88c807SRodney W. Grimes 		case 'o':
330fde411d5SJuli Mallett 			parsefmt(optarg, 1);
331871e8d8cSMark Murray 			_fmt = 1;
3324b88c807SRodney W. Grimes 			break;
3334b88c807SRodney W. Grimes 		case 'p':
334a4c8a745SGarance A Drosehn 			add_list(&pidlist, optarg);
335a4c8a745SGarance A Drosehn 			/*
336a4c8a745SGarance A Drosehn 			 * Note: `-p' does not *set* xkeep, but any values
337a4c8a745SGarance A Drosehn 			 * from pidlist are checked before xkeep is.  That
338a4c8a745SGarance A Drosehn 			 * way they are always matched, even if the user
339a4c8a745SGarance A Drosehn 			 * specifies `-X'.
340a4c8a745SGarance A Drosehn 			 */
341a4c8a745SGarance A Drosehn 			nselectors++;
3424b88c807SRodney W. Grimes 			break;
343a4c8a745SGarance A Drosehn #if 0
344a4c8a745SGarance A Drosehn 		case 'R':
345ba50b0e0SGarance A Drosehn 			/*-
346352b6523SGarance A Drosehn 			 * XXX - This un-standard option is still under
347352b6523SGarance A Drosehn 			 *	debate.  This is what SUSv3 defines as
348352b6523SGarance A Drosehn 			 *	the `-U' option, and while it would be
349352b6523SGarance A Drosehn 			 *	nice to have, it could cause even more
350352b6523SGarance A Drosehn 			 *	confusion to implement it as `-R'.
351352b6523SGarance A Drosehn 			 */
352a4c8a745SGarance A Drosehn 			add_list(&ruidlist, optarg);
353a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
354a4c8a745SGarance A Drosehn 			nselectors++;
355a4c8a745SGarance A Drosehn 			break;
356a4c8a745SGarance A Drosehn #endif
3574b88c807SRodney W. Grimes 		case 'r':
3584b88c807SRodney W. Grimes 			sortby = SORTCPU;
3594b88c807SRodney W. Grimes 			break;
3604b88c807SRodney W. Grimes 		case 'S':
3614b88c807SRodney W. Grimes 			sumrusage = 1;
3624b88c807SRodney W. Grimes 			break;
363a4c8a745SGarance A Drosehn #if 0
364a4c8a745SGarance A Drosehn 		case 's':
365ba50b0e0SGarance A Drosehn 			/*-
366352b6523SGarance A Drosehn 			 * XXX - This non-standard option is still under
367352b6523SGarance A Drosehn 			 *	debate.  This *is* supported on Solaris,
368352b6523SGarance A Drosehn 			 *	Linux, and IRIX, but conflicts with `-s'
369352b6523SGarance A Drosehn 			 *	on NetBSD and maybe some older BSD's.
370352b6523SGarance A Drosehn 			 */
371a4c8a745SGarance A Drosehn 			add_list(&sesslist, optarg);
372a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
373a4c8a745SGarance A Drosehn 			nselectors++;
374a4c8a745SGarance A Drosehn 			break;
375a4c8a745SGarance A Drosehn #endif
3764b88c807SRodney W. Grimes 		case 'T':
3774b88c807SRodney W. Grimes 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
3788beb1a2fSMarcel Moolenaar 				xo_errx(1, "stdin: not a terminal");
3794b88c807SRodney W. Grimes 			/* FALLTHROUGH */
380a4c8a745SGarance A Drosehn 		case 't':
381a4c8a745SGarance A Drosehn 			add_list(&ttylist, optarg);
382a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
383a4c8a745SGarance A Drosehn 			nselectors++;
3844b88c807SRodney W. Grimes 			break;
38573eb8310SPeter Wemm 		case 'U':
386a4c8a745SGarance A Drosehn 			/* This is what SUSv3 defines as the `-u' option. */
387a4c8a745SGarance A Drosehn 			add_list(&uidlist, optarg);
388a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
389a4c8a745SGarance A Drosehn 			nselectors++;
39073eb8310SPeter Wemm 			break;
3914b88c807SRodney W. Grimes 		case 'u':
392fde411d5SJuli Mallett 			parsefmt(ufmt, 0);
3934b88c807SRodney W. Grimes 			sortby = SORTCPU;
394871e8d8cSMark Murray 			_fmt = 1;
3954b88c807SRodney W. Grimes 			ufmt[0] = '\0';
3964b88c807SRodney W. Grimes 			break;
3974b88c807SRodney W. Grimes 		case 'v':
398fde411d5SJuli Mallett 			parsefmt(vfmt, 0);
3994b88c807SRodney W. Grimes 			sortby = SORTMEM;
400871e8d8cSMark Murray 			_fmt = 1;
4014b88c807SRodney W. Grimes 			vfmt[0] = '\0';
4024b88c807SRodney W. Grimes 			break;
4034b88c807SRodney W. Grimes 		case 'w':
4044b88c807SRodney W. Grimes 			if (wflag)
4054b88c807SRodney W. Grimes 				termwidth = UNLIMITED;
406ef1d40daSConrad Meyer 			else if (termwidth < 131 && termwidth != UNLIMITED)
4074b88c807SRodney W. Grimes 				termwidth = 131;
4084b88c807SRodney W. Grimes 			wflag++;
4094b88c807SRodney W. Grimes 			break;
410a4c8a745SGarance A Drosehn 		case 'X':
411a4c8a745SGarance A Drosehn 			/*
412a4c8a745SGarance A Drosehn 			 * Note that `-X' and `-x' are not standard "selector"
413a4c8a745SGarance A Drosehn 			 * options. For most selector-options, we check *all*
414a4c8a745SGarance A Drosehn 			 * processes to see if any are matched by the given
415a4c8a745SGarance A Drosehn 			 * value(s).  After we have a set of all the matched
416a4c8a745SGarance A Drosehn 			 * processes, then `-X' and `-x' govern whether we
417a4c8a745SGarance A Drosehn 			 * modify that *matched* set for processes which do
418a4c8a745SGarance A Drosehn 			 * not have a controlling terminal.  `-X' causes
419a4c8a745SGarance A Drosehn 			 * those processes to be deleted from the matched
420a4c8a745SGarance A Drosehn 			 * set, while `-x' causes them to be kept.
421a4c8a745SGarance A Drosehn 			 */
422a4c8a745SGarance A Drosehn 			xkeep = 0;
423a4c8a745SGarance A Drosehn 			break;
4244b88c807SRodney W. Grimes 		case 'x':
425a4c8a745SGarance A Drosehn 			xkeep = 1;
4264b88c807SRodney W. Grimes 			break;
4277304f61fSBrian Feldman 		case 'Z':
428fde411d5SJuli Mallett 			parsefmt(Zfmt, 0);
4297304f61fSBrian Feldman 			Zfmt[0] = '\0';
4307304f61fSBrian Feldman 			break;
4314b88c807SRodney W. Grimes 		case '?':
4324b88c807SRodney W. Grimes 		default:
4334b88c807SRodney W. Grimes 			usage();
4344b88c807SRodney W. Grimes 		}
4354b88c807SRodney W. Grimes 	argc -= optind;
4364b88c807SRodney W. Grimes 	argv += optind;
437c675340aSGarance A Drosehn 
438c675340aSGarance A Drosehn 	/*
439c675340aSGarance A Drosehn 	 * If there arguments after processing all the options, attempt
440c675340aSGarance A Drosehn 	 * to treat them as a list of process ids.
441c675340aSGarance A Drosehn 	 */
442c675340aSGarance A Drosehn 	while (*argv) {
443c675340aSGarance A Drosehn 		if (!isdigitch(**argv))
444c675340aSGarance A Drosehn 			break;
445c675340aSGarance A Drosehn 		add_list(&pidlist, *argv);
446c675340aSGarance A Drosehn 		argv++;
447c675340aSGarance A Drosehn 	}
448c675340aSGarance A Drosehn 	if (*argv) {
4498beb1a2fSMarcel Moolenaar 		xo_warnx("illegal argument: %s\n", *argv);
450c675340aSGarance A Drosehn 		usage();
451c675340aSGarance A Drosehn 	}
452a4c8a745SGarance A Drosehn 	if (optfatal)
453352b6523SGarance A Drosehn 		exit(1);		/* Error messages already printed. */
454352b6523SGarance A Drosehn 	if (xkeep < 0)			/* Neither -X nor -x was specified. */
455a4c8a745SGarance A Drosehn 		xkeep = xkeep_implied;
456a4c8a745SGarance A Drosehn 
457831c910aSRuslan Ermilov 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
458ec23a763SMarcelo Araujo 	if (kd == NULL)
4598beb1a2fSMarcel Moolenaar 		xo_errx(1, "%s", errbuf);
4604b88c807SRodney W. Grimes 
461871e8d8cSMark Murray 	if (!_fmt)
462fde411d5SJuli Mallett 		parsefmt(dfmt, 0);
4634b88c807SRodney W. Grimes 
464bf27a225SMath Ieu 	if (!all && nselectors == 0) {
465d822163fSGarance A Drosehn 		uidlist.l.ptr = malloc(sizeof(uid_t));
466d822163fSGarance A Drosehn 		if (uidlist.l.ptr == NULL)
4678beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
468a4c8a745SGarance A Drosehn 		nselectors = 1;
469a4c8a745SGarance A Drosehn 		uidlist.count = uidlist.maxcount = 1;
470d822163fSGarance A Drosehn 		*uidlist.l.uids = getuid();
471cf22dcfcSBrian Somers 	}
4724b88c807SRodney W. Grimes 
4734b88c807SRodney W. Grimes 	/*
4744b88c807SRodney W. Grimes 	 * scan requested variables, noting what structures are needed,
475bdfebd84SKris Kennaway 	 * and adjusting header widths as appropriate.
4764b88c807SRodney W. Grimes 	 */
4774b88c807SRodney W. Grimes 	scanvars();
478a4c8a745SGarance A Drosehn 
4794b88c807SRodney W. Grimes 	/*
480a4c8a745SGarance A Drosehn 	 * Get process list.  If the user requested just one selector-
481a4c8a745SGarance A Drosehn 	 * option, then kvm_getprocs can be asked to return just those
482a4c8a745SGarance A Drosehn 	 * processes.  Otherwise, have it return all processes, and
483a4c8a745SGarance A Drosehn 	 * then this routine will search that full list and select the
484a4c8a745SGarance A Drosehn 	 * processes which match any of the user's selector-options.
4854b88c807SRodney W. Grimes 	 */
486d75c1d83SDaniel Eischen 	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
48748b8c0deSScott Long 	flag = 0;
488a4c8a745SGarance A Drosehn 	if (nselectors == 1) {
4897bd42165SGarance A Drosehn 		if (gidlist.count == 1) {
4907bd42165SGarance A Drosehn 			what = KERN_PROC_RGID | showthreads;
4917bd42165SGarance A Drosehn 			flag = *gidlist.l.gids;
4927bd42165SGarance A Drosehn 			nselectors = 0;
4937bd42165SGarance A Drosehn 		} else if (pgrplist.count == 1) {
494a4c8a745SGarance A Drosehn 			what = KERN_PROC_PGRP | showthreads;
495d822163fSGarance A Drosehn 			flag = *pgrplist.l.pids;
496a4c8a745SGarance A Drosehn 			nselectors = 0;
4975c0a1c15SPiotr Pawel Stefaniak 		} else if (pidlist.count == 1 && directions == NONE) {
498a4c8a745SGarance A Drosehn 			what = KERN_PROC_PID | showthreads;
499d822163fSGarance A Drosehn 			flag = *pidlist.l.pids;
500a4c8a745SGarance A Drosehn 			nselectors = 0;
501a4c8a745SGarance A Drosehn 		} else if (ruidlist.count == 1) {
502a4c8a745SGarance A Drosehn 			what = KERN_PROC_RUID | showthreads;
503d822163fSGarance A Drosehn 			flag = *ruidlist.l.uids;
504a4c8a745SGarance A Drosehn 			nselectors = 0;
505a4c8a745SGarance A Drosehn 		} else if (sesslist.count == 1) {
506a4c8a745SGarance A Drosehn 			what = KERN_PROC_SESSION | showthreads;
507d822163fSGarance A Drosehn 			flag = *sesslist.l.pids;
508a4c8a745SGarance A Drosehn 			nselectors = 0;
509a4c8a745SGarance A Drosehn 		} else if (ttylist.count == 1) {
510a4c8a745SGarance A Drosehn 			what = KERN_PROC_TTY | showthreads;
511d822163fSGarance A Drosehn 			flag = *ttylist.l.ttys;
512a4c8a745SGarance A Drosehn 			nselectors = 0;
513a4c8a745SGarance A Drosehn 		} else if (uidlist.count == 1) {
514a4c8a745SGarance A Drosehn 			what = KERN_PROC_UID | showthreads;
515d822163fSGarance A Drosehn 			flag = *uidlist.l.uids;
516a4c8a745SGarance A Drosehn 			nselectors = 0;
517a4c8a745SGarance A Drosehn 		}
5184b88c807SRodney W. Grimes 	}
519d75c1d83SDaniel Eischen 
5204b88c807SRodney W. Grimes 	/*
5214b88c807SRodney W. Grimes 	 * select procs
5224b88c807SRodney W. Grimes 	 */
523a4c8a745SGarance A Drosehn 	nentries = -1;
5244e8b6a6fSGarance A Drosehn 	kp = kvm_getprocs(kd, what, flag, &nentries);
525d7026b96SEdward Tomasz Napierala 	/*
526d7026b96SEdward Tomasz Napierala 	 * Ignore ESRCH to preserve behaviour of "ps -p nonexistent-pid"
527d7026b96SEdward Tomasz Napierala 	 * not reporting an error.
528d7026b96SEdward Tomasz Napierala 	 */
529d7026b96SEdward Tomasz Napierala 	if ((kp == NULL && errno != ESRCH) || (kp != NULL && nentries < 0))
5308beb1a2fSMarcel Moolenaar 		xo_errx(1, "%s", kvm_geterr(kd));
531a4c8a745SGarance A Drosehn 	nkept = 0;
5325c0a1c15SPiotr Pawel Stefaniak 	pid_count.initial = pidlist.count;
5335c0a1c15SPiotr Pawel Stefaniak 	if (directions & DOWN)
5345c0a1c15SPiotr Pawel Stefaniak 		for (elem = 0; elem < pidlist.count; elem++)
5355c0a1c15SPiotr Pawel Stefaniak 			for (i = 0; i < nentries; i++) {
5365c0a1c15SPiotr Pawel Stefaniak 				if (kp[i].ki_ppid == kp[i].ki_pid)
5375c0a1c15SPiotr Pawel Stefaniak 					continue;
5385c0a1c15SPiotr Pawel Stefaniak 				if (kp[i].ki_ppid == pidlist.l.pids[elem]) {
5395c0a1c15SPiotr Pawel Stefaniak 					if (pidlist.count >= pidlist.maxcount)
5405c0a1c15SPiotr Pawel Stefaniak 						expand_list(&pidlist);
5415c0a1c15SPiotr Pawel Stefaniak 					pidlist.l.pids[pidlist.count++] = kp[i].ki_pid;
5425c0a1c15SPiotr Pawel Stefaniak 				}
5435c0a1c15SPiotr Pawel Stefaniak 			}
5445c0a1c15SPiotr Pawel Stefaniak 	pid_count.traversed = pidlist.count;
5455c0a1c15SPiotr Pawel Stefaniak 	if (directions & UP)
5465c0a1c15SPiotr Pawel Stefaniak 		for (elem = 0; elem < pidlist.count; elem++) {
5475c0a1c15SPiotr Pawel Stefaniak 			if (elem >= pid_count.initial && elem < pid_count.traversed)
5485c0a1c15SPiotr Pawel Stefaniak 				continue;
5495c0a1c15SPiotr Pawel Stefaniak 			for (i = 0; i < nentries; i++) {
5505c0a1c15SPiotr Pawel Stefaniak 				if (kp[i].ki_ppid == kp[i].ki_pid)
5515c0a1c15SPiotr Pawel Stefaniak 					continue;
5525c0a1c15SPiotr Pawel Stefaniak 				if (kp[i].ki_pid == pidlist.l.pids[elem]) {
5535c0a1c15SPiotr Pawel Stefaniak 					if (pidlist.count >= pidlist.maxcount)
5545c0a1c15SPiotr Pawel Stefaniak 						expand_list(&pidlist);
5555c0a1c15SPiotr Pawel Stefaniak 					pidlist.l.pids[pidlist.count++] = kp[i].ki_ppid;
5565c0a1c15SPiotr Pawel Stefaniak 				}
5575c0a1c15SPiotr Pawel Stefaniak 			}
5585c0a1c15SPiotr Pawel Stefaniak 		}
5594e8b6a6fSGarance A Drosehn 	if (nentries > 0) {
5604b88c807SRodney W. Grimes 		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
5618beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
5624b88c807SRodney W. Grimes 		for (i = nentries; --i >= 0; ++kp) {
563a4c8a745SGarance A Drosehn 			/*
564a4c8a745SGarance A Drosehn 			 * If the user specified multiple selection-criteria,
565a4c8a745SGarance A Drosehn 			 * then keep any process matched by the inclusive OR
566a4c8a745SGarance A Drosehn 			 * of all the selection-criteria given.
567a4c8a745SGarance A Drosehn 			 */
568a4c8a745SGarance A Drosehn 			if (pidlist.count > 0) {
569a4c8a745SGarance A Drosehn 				for (elem = 0; elem < pidlist.count; elem++)
570d822163fSGarance A Drosehn 					if (kp->ki_pid == pidlist.l.pids[elem])
571a4c8a745SGarance A Drosehn 						goto keepit;
572a4c8a745SGarance A Drosehn 			}
573a4c8a745SGarance A Drosehn 			/*
574a4c8a745SGarance A Drosehn 			 * Note that we had to process pidlist before
575a4c8a745SGarance A Drosehn 			 * filtering out processes which do not have
576a4c8a745SGarance A Drosehn 			 * a controlling terminal.
577a4c8a745SGarance A Drosehn 			 */
578a4c8a745SGarance A Drosehn 			if (xkeep == 0) {
579a4c8a745SGarance A Drosehn 				if ((kp->ki_tdev == NODEV ||
580a4c8a745SGarance A Drosehn 				    (kp->ki_flag & P_CONTROLT) == 0))
581a4c8a745SGarance A Drosehn 					continue;
582a4c8a745SGarance A Drosehn 			}
583a4c8a745SGarance A Drosehn 			if (nselectors == 0)
584a4c8a745SGarance A Drosehn 				goto keepit;
585a4c8a745SGarance A Drosehn 			if (gidlist.count > 0) {
586a4c8a745SGarance A Drosehn 				for (elem = 0; elem < gidlist.count; elem++)
587d822163fSGarance A Drosehn 					if (kp->ki_rgid == gidlist.l.gids[elem])
588a4c8a745SGarance A Drosehn 						goto keepit;
589a4c8a745SGarance A Drosehn 			}
59013767130SBryan Drewery 			if (jidlist.count > 0) {
59113767130SBryan Drewery 				for (elem = 0; elem < jidlist.count; elem++)
59213767130SBryan Drewery 					if (kp->ki_jid == jidlist.l.jids[elem])
59313767130SBryan Drewery 						goto keepit;
59413767130SBryan Drewery 			}
595a4c8a745SGarance A Drosehn 			if (pgrplist.count > 0) {
596a4c8a745SGarance A Drosehn 				for (elem = 0; elem < pgrplist.count; elem++)
597d822163fSGarance A Drosehn 					if (kp->ki_pgid ==
598d822163fSGarance A Drosehn 					    pgrplist.l.pids[elem])
599a4c8a745SGarance A Drosehn 						goto keepit;
600a4c8a745SGarance A Drosehn 			}
601a4c8a745SGarance A Drosehn 			if (ruidlist.count > 0) {
602a4c8a745SGarance A Drosehn 				for (elem = 0; elem < ruidlist.count; elem++)
603d822163fSGarance A Drosehn 					if (kp->ki_ruid ==
604d822163fSGarance A Drosehn 					    ruidlist.l.uids[elem])
605a4c8a745SGarance A Drosehn 						goto keepit;
606a4c8a745SGarance A Drosehn 			}
607a4c8a745SGarance A Drosehn 			if (sesslist.count > 0) {
608a4c8a745SGarance A Drosehn 				for (elem = 0; elem < sesslist.count; elem++)
609d822163fSGarance A Drosehn 					if (kp->ki_sid == sesslist.l.pids[elem])
610a4c8a745SGarance A Drosehn 						goto keepit;
611a4c8a745SGarance A Drosehn 			}
612a4c8a745SGarance A Drosehn 			if (ttylist.count > 0) {
613a4c8a745SGarance A Drosehn 				for (elem = 0; elem < ttylist.count; elem++)
614d822163fSGarance A Drosehn 					if (kp->ki_tdev == ttylist.l.ttys[elem])
615a4c8a745SGarance A Drosehn 						goto keepit;
616a4c8a745SGarance A Drosehn 			}
617a4c8a745SGarance A Drosehn 			if (uidlist.count > 0) {
618a4c8a745SGarance A Drosehn 				for (elem = 0; elem < uidlist.count; elem++)
619d822163fSGarance A Drosehn 					if (kp->ki_uid == uidlist.l.uids[elem])
620a4c8a745SGarance A Drosehn 						goto keepit;
621a4c8a745SGarance A Drosehn 			}
622a4c8a745SGarance A Drosehn 			/*
623a4c8a745SGarance A Drosehn 			 * This process did not match any of the user's
624a4c8a745SGarance A Drosehn 			 * selector-options, so skip the process.
625a4c8a745SGarance A Drosehn 			 */
626a4c8a745SGarance A Drosehn 			continue;
627a4c8a745SGarance A Drosehn 
628a4c8a745SGarance A Drosehn 		keepit:
6294bac4483SGarance A Drosehn 			next_KINFO = &kinfo[nkept];
6304bac4483SGarance A Drosehn 			next_KINFO->ki_p = kp;
631044fce53SBrian Somers 			next_KINFO->ki_d.level = 0;
632044fce53SBrian Somers 			next_KINFO->ki_d.prefix = NULL;
6334bac4483SGarance A Drosehn 			next_KINFO->ki_pcpu = getpcpu(next_KINFO);
6344bac4483SGarance A Drosehn 			if (sortby == SORTMEM)
6354bac4483SGarance A Drosehn 				next_KINFO->ki_memsize = kp->ki_tsize +
6364bac4483SGarance A Drosehn 				    kp->ki_dsize + kp->ki_ssize;
6374b88c807SRodney W. Grimes 			if (needuser)
6384bac4483SGarance A Drosehn 				saveuser(next_KINFO);
639a4c8a745SGarance A Drosehn 			nkept++;
6404b88c807SRodney W. Grimes 		}
6414e8b6a6fSGarance A Drosehn 	}
6426a2d726bSJordan K. Hubbard 
6436a2d726bSJordan K. Hubbard 	sizevars();
6446a2d726bSJordan K. Hubbard 
6451d1143ecSEdward Tomasz Napierala 	if (nkept == 0) {
6464b88c807SRodney W. Grimes 		printheader();
647e17a2944SYan-Hao Wang 		if (xo_finish() < 0)
648e17a2944SYan-Hao Wang 			xo_err(1, "stdout");
649f8c9c11cSWill Andrews 		exit(1);
6501d1143ecSEdward Tomasz Napierala 	}
651a4c8a745SGarance A Drosehn 
6524b88c807SRodney W. Grimes 	/*
6534b88c807SRodney W. Grimes 	 * sort proc list
6544b88c807SRodney W. Grimes 	 */
655a4c8a745SGarance A Drosehn 	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
656044fce53SBrian Somers 
657044fce53SBrian Somers 	/*
658044fce53SBrian Somers 	 * We want things in descendant order
659044fce53SBrian Somers 	 */
660044fce53SBrian Somers 	if (descendancy)
661044fce53SBrian Somers 		descendant_sort(kinfo, nkept);
662044fce53SBrian Somers 
6631d1143ecSEdward Tomasz Napierala 
6644b88c807SRodney W. Grimes 	/*
6651d1143ecSEdward Tomasz Napierala 	 * Prepare formatted output.
6661d1143ecSEdward Tomasz Napierala 	 */
6671d1143ecSEdward Tomasz Napierala 	for (i = 0; i < nkept; i++)
6681d1143ecSEdward Tomasz Napierala 		format_output(&kinfo[i]);
6691d1143ecSEdward Tomasz Napierala 
6701d1143ecSEdward Tomasz Napierala 	/*
6711d1143ecSEdward Tomasz Napierala 	 * Print header.
6721d1143ecSEdward Tomasz Napierala 	 */
6738beb1a2fSMarcel Moolenaar 	xo_open_container("process-information");
6741d1143ecSEdward Tomasz Napierala 	printheader();
6758beb1a2fSMarcel Moolenaar 	if (xo_get_style(NULL) != XO_STYLE_TEXT)
6768beb1a2fSMarcel Moolenaar 		termwidth = UNLIMITED;
6771d1143ecSEdward Tomasz Napierala 
6781d1143ecSEdward Tomasz Napierala 	/*
6791d1143ecSEdward Tomasz Napierala 	 * Output formatted lines.
6804b88c807SRodney W. Grimes 	 */
6818beb1a2fSMarcel Moolenaar 	xo_open_list("process");
682a4c8a745SGarance A Drosehn 	for (i = lineno = 0; i < nkept; i++) {
6831d1143ecSEdward Tomasz Napierala 		linelen = 0;
6848beb1a2fSMarcel Moolenaar 		xo_open_instance("process");
685bdf8ab46SGarance A Drosehn 		STAILQ_FOREACH(vent, &varlist, next_ve) {
6861d1143ecSEdward Tomasz Napierala 			ks = STAILQ_FIRST(&kinfo[i].ki_ks);
6871d1143ecSEdward Tomasz Napierala 			STAILQ_REMOVE_HEAD(&kinfo[i].ki_ks, ks_next);
68838494effSUlrich Spörlein 			/* Truncate rightmost column if necessary.  */
6898beb1a2fSMarcel Moolenaar 			fwidthmax = _POSIX2_LINE_MAX;
6901d1143ecSEdward Tomasz Napierala 			if (STAILQ_NEXT(vent, next_ve) == NULL &&
6911d1143ecSEdward Tomasz Napierala 			   termwidth != UNLIMITED && ks->ks_str != NULL) {
6921d1143ecSEdward Tomasz Napierala 				left = termwidth - linelen;
6931d1143ecSEdward Tomasz Napierala 				if (left > 0 && left < (int)strlen(ks->ks_str))
6948beb1a2fSMarcel Moolenaar 					fwidthmax = left;
6951d1143ecSEdward Tomasz Napierala 			}
6968beb1a2fSMarcel Moolenaar 
6971d1143ecSEdward Tomasz Napierala 			str = ks->ks_str;
6981d1143ecSEdward Tomasz Napierala 			if (str == NULL)
6991d1143ecSEdward Tomasz Napierala 				str = "-";
7001d1143ecSEdward Tomasz Napierala 			/* No padding for the last column, if it's LJUST. */
7018beb1a2fSMarcel Moolenaar 			fwidthmin = (xo_get_style(NULL) != XO_STYLE_TEXT ||
7028beb1a2fSMarcel Moolenaar 			    (STAILQ_NEXT(vent, next_ve) == NULL &&
7038beb1a2fSMarcel Moolenaar 			    (vent->var->flag & LJUST))) ? 0 : vent->var->width;
704aa8ab146SYuri Pankov 			snprintf(fmtbuf, sizeof(fmtbuf), "{:%s/%%%s%d..%dhs}",
705c6a5ff71SEitan Adler 			    vent->var->field ? vent->var->field : vent->var->name,
7068beb1a2fSMarcel Moolenaar 			    (vent->var->flag & LJUST) ? "-" : "",
7078beb1a2fSMarcel Moolenaar 			    fwidthmin, fwidthmax);
7088beb1a2fSMarcel Moolenaar 			xo_emit(fmtbuf, str);
7098beb1a2fSMarcel Moolenaar 			linelen += fwidthmin;
7101d1143ecSEdward Tomasz Napierala 
7111d1143ecSEdward Tomasz Napierala 			if (ks->ks_str != NULL) {
7121d1143ecSEdward Tomasz Napierala 				free(ks->ks_str);
7131d1143ecSEdward Tomasz Napierala 				ks->ks_str = NULL;
7141d1143ecSEdward Tomasz Napierala 			}
7151d1143ecSEdward Tomasz Napierala 			free(ks);
7161d1143ecSEdward Tomasz Napierala 			ks = NULL;
7171d1143ecSEdward Tomasz Napierala 
7181d1143ecSEdward Tomasz Napierala 			if (STAILQ_NEXT(vent, next_ve) != NULL) {
7198beb1a2fSMarcel Moolenaar 				xo_emit("{P: }");
7201d1143ecSEdward Tomasz Napierala 				linelen++;
7211d1143ecSEdward Tomasz Napierala 			}
7224b88c807SRodney W. Grimes 		}
7238beb1a2fSMarcel Moolenaar 	        xo_emit("\n");
7248beb1a2fSMarcel Moolenaar 		xo_close_instance("process");
7254b88c807SRodney W. Grimes 		if (prtheader && lineno++ == prtheader - 4) {
7268beb1a2fSMarcel Moolenaar 			xo_emit("\n");
7274b88c807SRodney W. Grimes 			printheader();
7284b88c807SRodney W. Grimes 			lineno = 0;
7294b88c807SRodney W. Grimes 		}
7304b88c807SRodney W. Grimes 	}
7318beb1a2fSMarcel Moolenaar 	xo_close_list("process");
7328beb1a2fSMarcel Moolenaar 	xo_close_container("process-information");
733e17a2944SYan-Hao Wang 	if (xo_finish() < 0)
734e17a2944SYan-Hao Wang 		xo_err(1, "stdout");
7358beb1a2fSMarcel Moolenaar 
736a4c8a745SGarance A Drosehn 	free_list(&gidlist);
73713767130SBryan Drewery 	free_list(&jidlist);
738a4c8a745SGarance A Drosehn 	free_list(&pidlist);
739a4c8a745SGarance A Drosehn 	free_list(&pgrplist);
740a4c8a745SGarance A Drosehn 	free_list(&ruidlist);
741a4c8a745SGarance A Drosehn 	free_list(&sesslist);
742a4c8a745SGarance A Drosehn 	free_list(&ttylist);
743a4c8a745SGarance A Drosehn 	free_list(&uidlist);
744044fce53SBrian Somers 	for (i = 0; i < nkept; i++)
745044fce53SBrian Somers 		free(kinfo[i].ki_d.prefix);
746044fce53SBrian Somers 	free(kinfo);
7472e6c6ac4SGarance A Drosehn 
7484b88c807SRodney W. Grimes 	exit(eval);
7494b88c807SRodney W. Grimes }
7504b88c807SRodney W. Grimes 
751a4c8a745SGarance A Drosehn static int
addelem_gid(struct listinfo * inf,const char * elem)752a4c8a745SGarance A Drosehn addelem_gid(struct listinfo *inf, const char *elem)
7534e8b6a6fSGarance A Drosehn {
754a4c8a745SGarance A Drosehn 	struct group *grp;
755a4c8a745SGarance A Drosehn 	const char *nameorID;
756a4c8a745SGarance A Drosehn 	char *endp;
7570b42be7cSGarance A Drosehn 	u_long bigtemp;
7584e8b6a6fSGarance A Drosehn 
759a4c8a745SGarance A Drosehn 	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
760a4c8a745SGarance A Drosehn 		if (*elem == '\0')
7618beb1a2fSMarcel Moolenaar 			xo_warnx("Invalid (zero-length) %s name", inf->lname);
762a4c8a745SGarance A Drosehn 		else
7638beb1a2fSMarcel Moolenaar 			xo_warnx("%s name too long: %s", inf->lname, elem);
764a4c8a745SGarance A Drosehn 		optfatal = 1;
765352b6523SGarance A Drosehn 		return (0);		/* Do not add this value. */
7664e8b6a6fSGarance A Drosehn 	}
767a4c8a745SGarance A Drosehn 
7684e8b6a6fSGarance A Drosehn 	/*
769a4c8a745SGarance A Drosehn 	 * SUSv3 states that `ps -G grouplist' should match "real-group
770a4c8a745SGarance A Drosehn 	 * ID numbers", and does not mention group-names.  I do want to
771a4c8a745SGarance A Drosehn 	 * also support group-names, so this tries for a group-id first,
772a4c8a745SGarance A Drosehn 	 * and only tries for a name if that doesn't work.  This is the
773a4c8a745SGarance A Drosehn 	 * opposite order of what is done in addelem_uid(), but in
774a4c8a745SGarance A Drosehn 	 * practice the order would only matter for group-names which
775a4c8a745SGarance A Drosehn 	 * are all-numeric.
7764e8b6a6fSGarance A Drosehn 	 */
777a4c8a745SGarance A Drosehn 	grp = NULL;
778a4c8a745SGarance A Drosehn 	nameorID = "named";
779a4c8a745SGarance A Drosehn 	errno = 0;
7800b42be7cSGarance A Drosehn 	bigtemp = strtoul(elem, &endp, 10);
7810b42be7cSGarance A Drosehn 	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
782a4c8a745SGarance A Drosehn 		nameorID = "name or ID matches";
7830b42be7cSGarance A Drosehn 		grp = getgrgid((gid_t)bigtemp);
784a4c8a745SGarance A Drosehn 	}
785a4c8a745SGarance A Drosehn 	if (grp == NULL)
786a4c8a745SGarance A Drosehn 		grp = getgrnam(elem);
787a4c8a745SGarance A Drosehn 	if (grp == NULL) {
7888beb1a2fSMarcel Moolenaar 		xo_warnx("No %s %s '%s'", inf->lname, nameorID, elem);
789a4c8a745SGarance A Drosehn 		optfatal = 1;
790c23b00b7SGarance A Drosehn 		return (0);
791a4c8a745SGarance A Drosehn 	}
792a4c8a745SGarance A Drosehn 	if (inf->count >= inf->maxcount)
793a4c8a745SGarance A Drosehn 		expand_list(inf);
794d822163fSGarance A Drosehn 	inf->l.gids[(inf->count)++] = grp->gr_gid;
795a4c8a745SGarance A Drosehn 	return (1);
796a4c8a745SGarance A Drosehn }
797a4c8a745SGarance A Drosehn 
798a4c8a745SGarance A Drosehn static int
addelem_jid(struct listinfo * inf,const char * elem)79913767130SBryan Drewery addelem_jid(struct listinfo *inf, const char *elem)
80013767130SBryan Drewery {
80113767130SBryan Drewery 	int tempid;
80213767130SBryan Drewery 
80313767130SBryan Drewery 	if (*elem == '\0') {
804e17a2944SYan-Hao Wang 		xo_warnx("Invalid (zero-length) jail id");
80513767130SBryan Drewery 		optfatal = 1;
80613767130SBryan Drewery 		return (0);		/* Do not add this value. */
80713767130SBryan Drewery 	}
80813767130SBryan Drewery 
80913767130SBryan Drewery 	tempid = jail_getid(elem);
81013767130SBryan Drewery 	if (tempid < 0) {
811e17a2944SYan-Hao Wang 		xo_warnx("Invalid %s: %s", inf->lname, elem);
81213767130SBryan Drewery 		optfatal = 1;
81313767130SBryan Drewery 		return (0);
81413767130SBryan Drewery 	}
81513767130SBryan Drewery 
81613767130SBryan Drewery 	if (inf->count >= inf->maxcount)
81713767130SBryan Drewery 		expand_list(inf);
81813767130SBryan Drewery 	inf->l.jids[(inf->count)++] = tempid;
81913767130SBryan Drewery 	return (1);
82013767130SBryan Drewery }
82113767130SBryan Drewery 
82213767130SBryan Drewery static int
addelem_pid(struct listinfo * inf,const char * elem)823a4c8a745SGarance A Drosehn addelem_pid(struct listinfo *inf, const char *elem)
824a4c8a745SGarance A Drosehn {
825a4c8a745SGarance A Drosehn 	char *endp;
826ca62e195SGarance A Drosehn 	long tempid;
827a4c8a745SGarance A Drosehn 
828de1702f4SGarance A Drosehn 	if (*elem == '\0') {
8298beb1a2fSMarcel Moolenaar 		xo_warnx("Invalid (zero-length) process id");
830de1702f4SGarance A Drosehn 		optfatal = 1;
831de1702f4SGarance A Drosehn 		return (0);		/* Do not add this value. */
83225113083SGarance A Drosehn 	}
83325113083SGarance A Drosehn 
834a4c8a745SGarance A Drosehn 	errno = 0;
835a4c8a745SGarance A Drosehn 	tempid = strtol(elem, &endp, 10);
836a4c8a745SGarance A Drosehn 	if (*endp != '\0' || tempid < 0 || elem == endp) {
8378beb1a2fSMarcel Moolenaar 		xo_warnx("Invalid %s: %s", inf->lname, elem);
8384e8b6a6fSGarance A Drosehn 		errno = ERANGE;
83964b0bf0bSPawel Jakub Dawidek 	} else if (errno != 0 || tempid > pid_max) {
8408beb1a2fSMarcel Moolenaar 		xo_warnx("%s too large: %s", inf->lname, elem);
8414e8b6a6fSGarance A Drosehn 		errno = ERANGE;
8424e8b6a6fSGarance A Drosehn 	}
8434e8b6a6fSGarance A Drosehn 	if (errno == ERANGE) {
844a4c8a745SGarance A Drosehn 		optfatal = 1;
845c23b00b7SGarance A Drosehn 		return (0);
8464e8b6a6fSGarance A Drosehn 	}
847a4c8a745SGarance A Drosehn 	if (inf->count >= inf->maxcount)
848a4c8a745SGarance A Drosehn 		expand_list(inf);
849d822163fSGarance A Drosehn 	inf->l.pids[(inf->count)++] = tempid;
850a4c8a745SGarance A Drosehn 	return (1);
8514e8b6a6fSGarance A Drosehn }
8524e8b6a6fSGarance A Drosehn 
85323b8efadSGarance A Drosehn /*-
85423b8efadSGarance A Drosehn  * The user can specify a device via one of three formats:
8558a529f59SJohn Baldwin  *     1) fully qualified, e.g.:     /dev/ttyp0 /dev/console	/dev/pts/0
8568a529f59SJohn Baldwin  *     2) missing "/dev", e.g.:      ttyp0      console		pts/0
8578a529f59SJohn Baldwin  *     3) two-letters, e.g.:         p0         co		0
85823b8efadSGarance A Drosehn  *        (matching letters that would be seen in the "TT" column)
85923b8efadSGarance A Drosehn  */
860a4c8a745SGarance A Drosehn static int
addelem_tty(struct listinfo * inf,const char * elem)861a4c8a745SGarance A Drosehn addelem_tty(struct listinfo *inf, const char *elem)
862cf22dcfcSBrian Somers {
863a4c8a745SGarance A Drosehn 	const char *ttypath;
864ca62e195SGarance A Drosehn 	struct stat sb;
8658a529f59SJohn Baldwin 	char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
866a4c8a745SGarance A Drosehn 
86723b8efadSGarance A Drosehn 	ttypath = NULL;
868f2fbfae6SGarance A Drosehn 	pathbuf2[0] = '\0';
8698a529f59SJohn Baldwin 	pathbuf3[0] = '\0';
87023b8efadSGarance A Drosehn 	switch (*elem) {
87123b8efadSGarance A Drosehn 	case '/':
872a4c8a745SGarance A Drosehn 		ttypath = elem;
87323b8efadSGarance A Drosehn 		break;
87423b8efadSGarance A Drosehn 	case 'c':
87523b8efadSGarance A Drosehn 		if (strcmp(elem, "co") == 0) {
87623b8efadSGarance A Drosehn 			ttypath = _PATH_CONSOLE;
87723b8efadSGarance A Drosehn 			break;
87823b8efadSGarance A Drosehn 		}
87923b8efadSGarance A Drosehn 		/* FALLTHROUGH */
88023b8efadSGarance A Drosehn 	default:
88123b8efadSGarance A Drosehn 		strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
882a4c8a745SGarance A Drosehn 		strlcat(pathbuf, elem, sizeof(pathbuf));
883a4c8a745SGarance A Drosehn 		ttypath = pathbuf;
884f2fbfae6SGarance A Drosehn 		if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
88523b8efadSGarance A Drosehn 			break;
8868a529f59SJohn Baldwin 		if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
8878a529f59SJohn Baldwin 			break;
88823b8efadSGarance A Drosehn 		if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
88923b8efadSGarance A Drosehn 			break;
890f2fbfae6SGarance A Drosehn 		/* Check to see if /dev/tty${elem} exists */
891f2fbfae6SGarance A Drosehn 		strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
892f2fbfae6SGarance A Drosehn 		strlcat(pathbuf2, elem, sizeof(pathbuf2));
893f2fbfae6SGarance A Drosehn 		if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
89423b8efadSGarance A Drosehn 			/* No need to repeat stat() && S_ISCHR() checks */
89523b8efadSGarance A Drosehn 			ttypath = NULL;
89623b8efadSGarance A Drosehn 			break;
897a4c8a745SGarance A Drosehn 		}
8988a529f59SJohn Baldwin 		/* Check to see if /dev/pts/${elem} exists */
8998a529f59SJohn Baldwin 		strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
9008a529f59SJohn Baldwin 		strlcat(pathbuf3, elem, sizeof(pathbuf3));
9018a529f59SJohn Baldwin 		if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
9028a529f59SJohn Baldwin 			/* No need to repeat stat() && S_ISCHR() checks */
9038a529f59SJohn Baldwin 			ttypath = NULL;
9048a529f59SJohn Baldwin 			break;
9058a529f59SJohn Baldwin 		}
90623b8efadSGarance A Drosehn 		break;
90723b8efadSGarance A Drosehn 	}
90823b8efadSGarance A Drosehn 	if (ttypath) {
909a4c8a745SGarance A Drosehn 		if (stat(ttypath, &sb) == -1) {
9108a529f59SJohn Baldwin 			if (pathbuf3[0] != '\0')
9118beb1a2fSMarcel Moolenaar 				xo_warn("%s, %s, and %s", pathbuf3, pathbuf2,
9128a529f59SJohn Baldwin 				    ttypath);
913f2fbfae6SGarance A Drosehn 			else
9148beb1a2fSMarcel Moolenaar 				xo_warn("%s", ttypath);
915a4c8a745SGarance A Drosehn 			optfatal = 1;
916c23b00b7SGarance A Drosehn 			return (0);
917a4c8a745SGarance A Drosehn 		}
918a4c8a745SGarance A Drosehn 		if (!S_ISCHR(sb.st_mode)) {
9198a529f59SJohn Baldwin 			if (pathbuf3[0] != '\0')
9208beb1a2fSMarcel Moolenaar 				xo_warnx("%s, %s, and %s: Not a terminal",
9218a529f59SJohn Baldwin 				    pathbuf3, pathbuf2, ttypath);
922f2fbfae6SGarance A Drosehn 			else
9238beb1a2fSMarcel Moolenaar 				xo_warnx("%s: Not a terminal", ttypath);
924a4c8a745SGarance A Drosehn 			optfatal = 1;
925c23b00b7SGarance A Drosehn 			return (0);
926a4c8a745SGarance A Drosehn 		}
92723b8efadSGarance A Drosehn 	}
928a4c8a745SGarance A Drosehn 	if (inf->count >= inf->maxcount)
929a4c8a745SGarance A Drosehn 		expand_list(inf);
930d822163fSGarance A Drosehn 	inf->l.ttys[(inf->count)++] = sb.st_rdev;
931a4c8a745SGarance A Drosehn 	return (1);
932a4c8a745SGarance A Drosehn }
933a4c8a745SGarance A Drosehn 
934a4c8a745SGarance A Drosehn static int
addelem_uid(struct listinfo * inf,const char * elem)935a4c8a745SGarance A Drosehn addelem_uid(struct listinfo *inf, const char *elem)
936a4c8a745SGarance A Drosehn {
937cf22dcfcSBrian Somers 	struct passwd *pwd;
938a4c8a745SGarance A Drosehn 	char *endp;
9390b42be7cSGarance A Drosehn 	u_long bigtemp;
940cf22dcfcSBrian Somers 
941a4c8a745SGarance A Drosehn 	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
942a4c8a745SGarance A Drosehn 		if (*elem == '\0')
9438beb1a2fSMarcel Moolenaar 			xo_warnx("Invalid (zero-length) %s name", inf->lname);
944a4c8a745SGarance A Drosehn 		else
9458beb1a2fSMarcel Moolenaar 			xo_warnx("%s name too long: %s", inf->lname, elem);
946a4c8a745SGarance A Drosehn 		optfatal = 1;
947352b6523SGarance A Drosehn 		return (0);		/* Do not add this value. */
948a4c8a745SGarance A Drosehn 	}
949cf22dcfcSBrian Somers 
950a4c8a745SGarance A Drosehn 	pwd = getpwnam(elem);
951a4c8a745SGarance A Drosehn 	if (pwd == NULL) {
952a4c8a745SGarance A Drosehn 		errno = 0;
9530b42be7cSGarance A Drosehn 		bigtemp = strtoul(elem, &endp, 10);
9540b42be7cSGarance A Drosehn 		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
9558beb1a2fSMarcel Moolenaar 			xo_warnx("No %s named '%s'", inf->lname, elem);
956a4c8a745SGarance A Drosehn 		else {
957a4c8a745SGarance A Drosehn 			/* The string is all digits, so it might be a userID. */
9580b42be7cSGarance A Drosehn 			pwd = getpwuid((uid_t)bigtemp);
959a4c8a745SGarance A Drosehn 			if (pwd == NULL)
9608beb1a2fSMarcel Moolenaar 				xo_warnx("No %s name or ID matches '%s'",
961a4c8a745SGarance A Drosehn 				    inf->lname, elem);
962cf22dcfcSBrian Somers 		}
963cf22dcfcSBrian Somers 	}
964a4c8a745SGarance A Drosehn 	if (pwd == NULL) {
965e3c4e1ddSGarance A Drosehn 		/*
966e3c4e1ddSGarance A Drosehn 		 * These used to be treated as minor warnings (and the
967e3c4e1ddSGarance A Drosehn 		 * option was simply ignored), but now they are fatal
968e3c4e1ddSGarance A Drosehn 		 * errors (and the command will be aborted).
969e3c4e1ddSGarance A Drosehn 		 */
970e3c4e1ddSGarance A Drosehn 		optfatal = 1;
971c23b00b7SGarance A Drosehn 		return (0);
972cf22dcfcSBrian Somers 	}
973a4c8a745SGarance A Drosehn 	if (inf->count >= inf->maxcount)
974a4c8a745SGarance A Drosehn 		expand_list(inf);
975d822163fSGarance A Drosehn 	inf->l.uids[(inf->count)++] = pwd->pw_uid;
976a4c8a745SGarance A Drosehn 	return (1);
977a4c8a745SGarance A Drosehn }
978cf22dcfcSBrian Somers 
979a4c8a745SGarance A Drosehn static void
add_list(struct listinfo * inf,const char * argp)980a4c8a745SGarance A Drosehn add_list(struct listinfo *inf, const char *argp)
981a4c8a745SGarance A Drosehn {
982a4c8a745SGarance A Drosehn 	const char *savep;
983a4c8a745SGarance A Drosehn 	char *cp, *endp;
984a4c8a745SGarance A Drosehn 	int toolong;
985ca62e195SGarance A Drosehn 	char elemcopy[PATH_MAX];
986a4c8a745SGarance A Drosehn 
98742856668SEd Maste 	if (*argp == '\0')
98842856668SEd Maste 		inf->addelem(inf, argp);
989a4c8a745SGarance A Drosehn 	while (*argp != '\0') {
990a4c8a745SGarance A Drosehn 		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
991a4c8a745SGarance A Drosehn 			argp++;
992a4c8a745SGarance A Drosehn 		savep = argp;
993a4c8a745SGarance A Drosehn 		toolong = 0;
994a4c8a745SGarance A Drosehn 		cp = elemcopy;
995a4c8a745SGarance A Drosehn 		if (strchr(T_SEP, *argp) == NULL) {
996a4c8a745SGarance A Drosehn 			endp = elemcopy + sizeof(elemcopy) - 1;
997a4c8a745SGarance A Drosehn 			while (*argp != '\0' && cp <= endp &&
998a4c8a745SGarance A Drosehn 			    strchr(W_SEP T_SEP, *argp) == NULL)
999a4c8a745SGarance A Drosehn 				*cp++ = *argp++;
1000a4c8a745SGarance A Drosehn 			if (cp > endp)
1001a4c8a745SGarance A Drosehn 				toolong = 1;
1002a4c8a745SGarance A Drosehn 		}
1003a4c8a745SGarance A Drosehn 		if (!toolong) {
1004a4c8a745SGarance A Drosehn 			*cp = '\0';
1005352b6523SGarance A Drosehn 			/*
1006a9626fb3SGarance A Drosehn 			 * Add this single element to the given list.
1007352b6523SGarance A Drosehn 			 */
1008a4c8a745SGarance A Drosehn 			inf->addelem(inf, elemcopy);
1009a4c8a745SGarance A Drosehn 		} else {
1010a4c8a745SGarance A Drosehn 			/*
1011a4c8a745SGarance A Drosehn 			 * The string is too long to copy.  Find the end
1012a4c8a745SGarance A Drosehn 			 * of the string to print out the warning message.
1013a4c8a745SGarance A Drosehn 			 */
1014a4c8a745SGarance A Drosehn 			while (*argp != '\0' && strchr(W_SEP T_SEP,
1015a4c8a745SGarance A Drosehn 			    *argp) == NULL)
1016a4c8a745SGarance A Drosehn 				argp++;
10178beb1a2fSMarcel Moolenaar 			xo_warnx("Value too long: %.*s", (int)(argp - savep),
1018a4c8a745SGarance A Drosehn 			    savep);
1019a4c8a745SGarance A Drosehn 			optfatal = 1;
1020a4c8a745SGarance A Drosehn 		}
1021a4c8a745SGarance A Drosehn 		/*
1022a4c8a745SGarance A Drosehn 		 * Skip over any number of trailing whitespace characters,
1023a4c8a745SGarance A Drosehn 		 * but only one (at most) trailing element-terminating
1024a4c8a745SGarance A Drosehn 		 * character.
1025a4c8a745SGarance A Drosehn 		 */
1026a4c8a745SGarance A Drosehn 		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
1027a4c8a745SGarance A Drosehn 			argp++;
1028a4c8a745SGarance A Drosehn 		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
1029a4c8a745SGarance A Drosehn 			argp++;
1030a4c8a745SGarance A Drosehn 			/* Catch case where string ended with a comma. */
1031a4c8a745SGarance A Drosehn 			if (*argp == '\0')
1032a4c8a745SGarance A Drosehn 				inf->addelem(inf, argp);
1033a4c8a745SGarance A Drosehn 		}
1034a4c8a745SGarance A Drosehn 	}
1035a4c8a745SGarance A Drosehn }
1036a4c8a745SGarance A Drosehn 
1037044fce53SBrian Somers static void
descendant_sort(KINFO * ki,int items)1038044fce53SBrian Somers descendant_sort(KINFO *ki, int items)
1039044fce53SBrian Somers {
1040044fce53SBrian Somers 	int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
1041044fce53SBrian Somers 	unsigned char *path;
1042044fce53SBrian Somers 	KINFO kn;
1043044fce53SBrian Somers 
1044044fce53SBrian Somers 	/*
1045044fce53SBrian Somers 	 * First, sort the entries by descendancy, tracking the descendancy
1046044fce53SBrian Somers 	 * depth in the ki_d.level field.
1047044fce53SBrian Somers 	 */
1048044fce53SBrian Somers 	src = 0;
1049044fce53SBrian Somers 	maxlvl = 0;
1050044fce53SBrian Somers 	while (src < items) {
1051044fce53SBrian Somers 		if (ki[src].ki_d.level) {
1052044fce53SBrian Somers 			src++;
1053044fce53SBrian Somers 			continue;
1054044fce53SBrian Somers 		}
1055044fce53SBrian Somers 		for (nsrc = 1; src + nsrc < items; nsrc++)
1056044fce53SBrian Somers 			if (!ki[src + nsrc].ki_d.level)
1057044fce53SBrian Somers 				break;
1058044fce53SBrian Somers 
1059044fce53SBrian Somers 		for (dst = 0; dst < items; dst++) {
1060044fce53SBrian Somers 			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
1061044fce53SBrian Somers 				continue;
1062044fce53SBrian Somers 			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
1063044fce53SBrian Somers 				break;
1064044fce53SBrian Somers 		}
1065044fce53SBrian Somers 
1066044fce53SBrian Somers 		if (dst == items) {
1067044fce53SBrian Somers 			src += nsrc;
1068044fce53SBrian Somers 			continue;
1069044fce53SBrian Somers 		}
1070044fce53SBrian Somers 
1071044fce53SBrian Somers 		for (ndst = 1; dst + ndst < items; ndst++)
1072044fce53SBrian Somers 			if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
1073044fce53SBrian Somers 				break;
1074044fce53SBrian Somers 
1075044fce53SBrian Somers 		for (n = src; n < src + nsrc; n++) {
1076044fce53SBrian Somers 			ki[n].ki_d.level += ki[dst].ki_d.level + 1;
1077044fce53SBrian Somers 			if (maxlvl < ki[n].ki_d.level)
1078044fce53SBrian Somers 				maxlvl = ki[n].ki_d.level;
1079044fce53SBrian Somers 		}
1080044fce53SBrian Somers 
1081044fce53SBrian Somers 		while (nsrc) {
1082044fce53SBrian Somers 			if (src < dst) {
1083044fce53SBrian Somers 				kn = ki[src];
1084044fce53SBrian Somers 				memmove(ki + src, ki + src + 1,
1085044fce53SBrian Somers 				    (dst - src + ndst - 1) * sizeof *ki);
1086044fce53SBrian Somers 				ki[dst + ndst - 1] = kn;
1087044fce53SBrian Somers 				nsrc--;
1088044fce53SBrian Somers 				dst--;
1089044fce53SBrian Somers 				ndst++;
1090044fce53SBrian Somers 			} else if (src != dst + ndst) {
1091044fce53SBrian Somers 				kn = ki[src];
1092044fce53SBrian Somers 				memmove(ki + dst + ndst + 1, ki + dst + ndst,
1093044fce53SBrian Somers 				    (src - dst - ndst) * sizeof *ki);
1094044fce53SBrian Somers 				ki[dst + ndst] = kn;
1095044fce53SBrian Somers 				ndst++;
1096044fce53SBrian Somers 				nsrc--;
1097044fce53SBrian Somers 				src++;
1098044fce53SBrian Somers 			} else {
1099044fce53SBrian Somers 				ndst += nsrc;
1100044fce53SBrian Somers 				src += nsrc;
1101044fce53SBrian Somers 				nsrc = 0;
1102044fce53SBrian Somers 			}
1103044fce53SBrian Somers 		}
1104044fce53SBrian Somers 	}
1105044fce53SBrian Somers 
1106044fce53SBrian Somers 	/*
1107044fce53SBrian Somers 	 * Now populate ki_d.prefix (instead of ki_d.level) with the command
1108044fce53SBrian Somers 	 * prefix used to show descendancies.
1109044fce53SBrian Somers 	 */
11103322d1c0SAlfonso 	path = calloc((maxlvl + 7) / 8, sizeof(unsigned char));
1111044fce53SBrian Somers 	for (src = 0; src < items; src++) {
1112044fce53SBrian Somers 		if ((lvl = ki[src].ki_d.level) == 0) {
1113044fce53SBrian Somers 			ki[src].ki_d.prefix = NULL;
1114044fce53SBrian Somers 			continue;
1115044fce53SBrian Somers 		}
1116044fce53SBrian Somers 		if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
11178beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
1118044fce53SBrian Somers 		for (n = 0; n < lvl - 2; n++) {
1119044fce53SBrian Somers 			ki[src].ki_d.prefix[n * 2] =
1120044fce53SBrian Somers 			    path[n / 8] & 1 << (n % 8) ? '|' : ' ';
1121044fce53SBrian Somers 			ki[src].ki_d.prefix[n * 2 + 1] = ' ';
1122044fce53SBrian Somers 		}
1123044fce53SBrian Somers 		if (n == lvl - 2) {
1124044fce53SBrian Somers 			/* Have I any more siblings? */
1125044fce53SBrian Somers 			for (siblings = 0, dst = src + 1; dst < items; dst++) {
1126044fce53SBrian Somers 				if (ki[dst].ki_d.level > lvl)
1127044fce53SBrian Somers 					continue;
1128044fce53SBrian Somers 				if (ki[dst].ki_d.level == lvl)
1129044fce53SBrian Somers 					siblings = 1;
1130044fce53SBrian Somers 				break;
1131044fce53SBrian Somers 			}
1132044fce53SBrian Somers 			if (siblings)
1133044fce53SBrian Somers 				path[n / 8] |= 1 << (n % 8);
1134044fce53SBrian Somers 			else
1135044fce53SBrian Somers 				path[n / 8] &= ~(1 << (n % 8));
1136044fce53SBrian Somers 			ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1137044fce53SBrian Somers 			ki[src].ki_d.prefix[n * 2 + 1] = '-';
1138044fce53SBrian Somers 			n++;
1139044fce53SBrian Somers 		}
1140044fce53SBrian Somers 		strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1141044fce53SBrian Somers 	}
1142044fce53SBrian Somers 	free(path);
1143044fce53SBrian Somers }
1144044fce53SBrian Somers 
1145a4c8a745SGarance A Drosehn static void *
expand_list(struct listinfo * inf)1146a4c8a745SGarance A Drosehn expand_list(struct listinfo *inf)
1147a4c8a745SGarance A Drosehn {
1148a4c8a745SGarance A Drosehn 	void *newlist;
1149ca62e195SGarance A Drosehn 	int newmax;
1150a4c8a745SGarance A Drosehn 
1151a4c8a745SGarance A Drosehn 	newmax = (inf->maxcount + 1) << 1;
1152d822163fSGarance A Drosehn 	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1153a4c8a745SGarance A Drosehn 	if (newlist == NULL) {
1154d822163fSGarance A Drosehn 		free(inf->l.ptr);
11558beb1a2fSMarcel Moolenaar 		xo_errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1156a4c8a745SGarance A Drosehn 	}
1157a4c8a745SGarance A Drosehn 	inf->maxcount = newmax;
1158d822163fSGarance A Drosehn 	inf->l.ptr = newlist;
1159a4c8a745SGarance A Drosehn 
1160a4c8a745SGarance A Drosehn 	return (newlist);
1161a4c8a745SGarance A Drosehn }
1162a4c8a745SGarance A Drosehn 
1163a4c8a745SGarance A Drosehn static void
free_list(struct listinfo * inf)1164a4c8a745SGarance A Drosehn free_list(struct listinfo *inf)
1165a4c8a745SGarance A Drosehn {
1166a4c8a745SGarance A Drosehn 
1167a4c8a745SGarance A Drosehn 	inf->count = inf->elemsize = inf->maxcount = 0;
1168d822163fSGarance A Drosehn 	if (inf->l.ptr != NULL)
1169d822163fSGarance A Drosehn 		free(inf->l.ptr);
1170a4c8a745SGarance A Drosehn 	inf->addelem = NULL;
1171a4c8a745SGarance A Drosehn 	inf->lname = NULL;
1172d822163fSGarance A Drosehn 	inf->l.ptr = NULL;
1173a4c8a745SGarance A Drosehn }
1174a4c8a745SGarance A Drosehn 
1175a4c8a745SGarance A Drosehn static void
init_list(struct listinfo * inf,addelem_rtn artn,int elemsize,const char * lname)1176a4c8a745SGarance A Drosehn init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1177a4c8a745SGarance A Drosehn     const char *lname)
1178a4c8a745SGarance A Drosehn {
1179a4c8a745SGarance A Drosehn 
1180a4c8a745SGarance A Drosehn 	inf->count = inf->maxcount = 0;
1181a4c8a745SGarance A Drosehn 	inf->elemsize = elemsize;
1182a4c8a745SGarance A Drosehn 	inf->addelem = artn;
1183a4c8a745SGarance A Drosehn 	inf->lname = lname;
1184d822163fSGarance A Drosehn 	inf->l.ptr = NULL;
1185cf22dcfcSBrian Somers }
1186cf22dcfcSBrian Somers 
1187fde411d5SJuli Mallett VARENT *
find_varentry(VAR * v)1188fde411d5SJuli Mallett find_varentry(VAR *v)
1189fde411d5SJuli Mallett {
1190fde411d5SJuli Mallett 	struct varent *vent;
1191fde411d5SJuli Mallett 
1192bdf8ab46SGarance A Drosehn 	STAILQ_FOREACH(vent, &varlist, next_ve) {
1193fde411d5SJuli Mallett 		if (strcmp(vent->var->name, v->name) == 0)
1194fde411d5SJuli Mallett 			return vent;
1195fde411d5SJuli Mallett 	}
1196fde411d5SJuli Mallett 	return NULL;
1197fde411d5SJuli Mallett }
1198fde411d5SJuli Mallett 
11994b88c807SRodney W. Grimes static void
scanvars(void)120046251ddeSWarner Losh scanvars(void)
12014b88c807SRodney W. Grimes {
12024b88c807SRodney W. Grimes 	struct varent *vent;
12034b88c807SRodney W. Grimes 	VAR *v;
12046a2d726bSJordan K. Hubbard 
1205bdf8ab46SGarance A Drosehn 	STAILQ_FOREACH(vent, &varlist, next_ve) {
12066a2d726bSJordan K. Hubbard 		v = vent->var;
12076a2d726bSJordan K. Hubbard 		if (v->flag & USER)
12086a2d726bSJordan K. Hubbard 			needuser = 1;
12096a2d726bSJordan K. Hubbard 		if (v->flag & COMM)
12106a2d726bSJordan K. Hubbard 			needcomm = 1;
12116a2d726bSJordan K. Hubbard 	}
12126a2d726bSJordan K. Hubbard }
12136a2d726bSJordan K. Hubbard 
12146a2d726bSJordan K. Hubbard static void
format_output(KINFO * ki)12151d1143ecSEdward Tomasz Napierala format_output(KINFO *ki)
12166a2d726bSJordan K. Hubbard {
12176a2d726bSJordan K. Hubbard 	struct varent *vent;
12186a2d726bSJordan K. Hubbard 	VAR *v;
12191d1143ecSEdward Tomasz Napierala 	KINFO_STR *ks;
12201d1143ecSEdward Tomasz Napierala 	char *str;
12211d1143ecSEdward Tomasz Napierala 	int len;
12226a2d726bSJordan K. Hubbard 
12231d1143ecSEdward Tomasz Napierala 	STAILQ_INIT(&ki->ki_ks);
1224bdf8ab46SGarance A Drosehn 	STAILQ_FOREACH(vent, &varlist, next_ve) {
12256a2d726bSJordan K. Hubbard 		v = vent->var;
12261d1143ecSEdward Tomasz Napierala 		str = (v->oproc)(ki, vent);
12271d1143ecSEdward Tomasz Napierala 		ks = malloc(sizeof(*ks));
12281d1143ecSEdward Tomasz Napierala 		if (ks == NULL)
12298beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
12301d1143ecSEdward Tomasz Napierala 		ks->ks_str = str;
12311d1143ecSEdward Tomasz Napierala 		STAILQ_INSERT_TAIL(&ki->ki_ks, ks, ks_next);
12321d1143ecSEdward Tomasz Napierala 		if (str != NULL) {
12331d1143ecSEdward Tomasz Napierala 			len = strlen(str);
12341d1143ecSEdward Tomasz Napierala 		} else
12351d1143ecSEdward Tomasz Napierala 			len = 1; /* "-" */
12361d1143ecSEdward Tomasz Napierala 		if (v->width < len)
12371d1143ecSEdward Tomasz Napierala 			v->width = len;
12386a2d726bSJordan K. Hubbard 	}
12396a2d726bSJordan K. Hubbard }
12406a2d726bSJordan K. Hubbard 
12416a2d726bSJordan K. Hubbard static void
sizevars(void)124246251ddeSWarner Losh sizevars(void)
12436a2d726bSJordan K. Hubbard {
12446a2d726bSJordan K. Hubbard 	struct varent *vent;
12456a2d726bSJordan K. Hubbard 	VAR *v;
12464b88c807SRodney W. Grimes 	int i;
12474b88c807SRodney W. Grimes 
1248bdf8ab46SGarance A Drosehn 	STAILQ_FOREACH(vent, &varlist, next_ve) {
12494b88c807SRodney W. Grimes 		v = vent->var;
125078b1878aSJuli Mallett 		i = strlen(vent->header);
12514b88c807SRodney W. Grimes 		if (v->width < i)
12524b88c807SRodney W. Grimes 			v->width = i;
12534b88c807SRodney W. Grimes 	}
12544b88c807SRodney W. Grimes }
12554b88c807SRodney W. Grimes 
1256871e8d8cSMark Murray static const char *
fmt(char ** (* fn)(kvm_t *,const struct kinfo_proc *,int),KINFO * ki,char * comm,char * thread,int maxlen)125746251ddeSWarner Losh fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
12581c67ef12SJohn Baldwin     char *comm, char *thread, int maxlen)
12594b88c807SRodney W. Grimes {
1260871e8d8cSMark Murray 	const char *s;
12614b88c807SRodney W. Grimes 
12621c67ef12SJohn Baldwin 	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm,
12639f0b6e5eSJohn Baldwin 	    showthreads && ki->ki_p->ki_numthreads > 1 ? thread : NULL, maxlen);
12644b88c807SRodney W. Grimes 	return (s);
12654b88c807SRodney W. Grimes }
12664b88c807SRodney W. Grimes 
12674b88c807SRodney W. Grimes static void
saveuser(KINFO * ki)126846251ddeSWarner Losh saveuser(KINFO *ki)
12694b88c807SRodney W. Grimes {
1270c7f893a4SMark Johnston 	char tdname[COMMLEN + 1];
12714b88c807SRodney W. Grimes 
12721f7d2501SKirk McKusick 	ki->ki_valid = 1;
127362e6ca0fSKonstantin Belousov 
12744b88c807SRodney W. Grimes 	/*
12754b88c807SRodney W. Grimes 	 * save arguments if needed
12764b88c807SRodney W. Grimes 	 */
1277dd693acfSGarance A Drosehn 	if (needcomm) {
1278c7f893a4SMark Johnston 		if (ki->ki_p->ki_stat == SZOMB) {
1279dd693acfSGarance A Drosehn 			ki->ki_args = strdup("<defunct>");
1280*092e2ff3SKonstantin Belousov 		} else {
1281c7f893a4SMark Johnston 			(void)snprintf(tdname, sizeof(tdname), "%s%s",
1282c7f893a4SMark Johnston 			    ki->ki_p->ki_tdname, ki->ki_p->ki_moretdname);
12835912ca59SDon Lewis 			ki->ki_args = fmt(kvm_getargv, ki,
1284c7f893a4SMark Johnston 			    ki->ki_p->ki_comm, tdname, COMMLEN * 2 + 1);
12855912ca59SDon Lewis 		}
1286bd6233fdSGarance A Drosehn 		if (ki->ki_args == NULL)
12878beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
12883ac5e955SJohn Dyson 	} else {
12894b88c807SRodney W. Grimes 		ki->ki_args = NULL;
12903ac5e955SJohn Dyson 	}
1291dd693acfSGarance A Drosehn 	if (needenv) {
129262e6ca0fSKonstantin Belousov 		ki->ki_env = fmt(kvm_getenvv, ki, (char *)NULL,
129362e6ca0fSKonstantin Belousov 		    (char *)NULL, 0);
1294dd693acfSGarance A Drosehn 		if (ki->ki_env == NULL)
12958beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
12963ac5e955SJohn Dyson 	} else {
12974b88c807SRodney W. Grimes 		ki->ki_env = NULL;
12984b88c807SRodney W. Grimes 	}
12993ac5e955SJohn Dyson }
13004b88c807SRodney W. Grimes 
13014bac4483SGarance A Drosehn /* A macro used to improve the readability of pscomp(). */
13024bac4483SGarance A Drosehn #define	DIFF_RETURN(a, b, field) do {	\
13034bac4483SGarance A Drosehn 	if ((a)->field != (b)->field)	\
13044bac4483SGarance A Drosehn 		return (((a)->field < (b)->field) ? -1 : 1); 	\
13054bac4483SGarance A Drosehn } while (0)
13064bac4483SGarance A Drosehn 
13074b88c807SRodney W. Grimes static int
pscomp(const void * a,const void * b)130846251ddeSWarner Losh pscomp(const void *a, const void *b)
13094b88c807SRodney W. Grimes {
13105bd7b1f3SGarance A Drosehn 	const KINFO *ka, *kb;
13114b88c807SRodney W. Grimes 
13125bd7b1f3SGarance A Drosehn 	ka = a;
13135bd7b1f3SGarance A Drosehn 	kb = b;
13145bd7b1f3SGarance A Drosehn 	/* SORTCPU and SORTMEM are sorted in descending order. */
13154bac4483SGarance A Drosehn 	if (sortby == SORTCPU)
13164bac4483SGarance A Drosehn 		DIFF_RETURN(kb, ka, ki_pcpu);
13174bac4483SGarance A Drosehn 	if (sortby == SORTMEM)
13184bac4483SGarance A Drosehn 		DIFF_RETURN(kb, ka, ki_memsize);
13195bd7b1f3SGarance A Drosehn 	/*
13205bd7b1f3SGarance A Drosehn 	 * TTY's are sorted in ascending order, except that all NODEV
13215bd7b1f3SGarance A Drosehn 	 * processes come before all processes with a device.
13225bd7b1f3SGarance A Drosehn 	 */
13234bac4483SGarance A Drosehn 	if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
13244bac4483SGarance A Drosehn 		if (ka->ki_p->ki_tdev == NODEV)
13255bd7b1f3SGarance A Drosehn 			return (-1);
13264bac4483SGarance A Drosehn 		if (kb->ki_p->ki_tdev == NODEV)
13275bd7b1f3SGarance A Drosehn 			return (1);
13284bac4483SGarance A Drosehn 		DIFF_RETURN(ka, kb, ki_p->ki_tdev);
13294bac4483SGarance A Drosehn 	}
13304bac4483SGarance A Drosehn 
1331b4b24324SGarance A Drosehn 	/* PID's and TID's (threads) are sorted in ascending order. */
13324bac4483SGarance A Drosehn 	DIFF_RETURN(ka, kb, ki_p->ki_pid);
1333b4b24324SGarance A Drosehn 	DIFF_RETURN(ka, kb, ki_p->ki_tid);
13345bd7b1f3SGarance A Drosehn 	return (0);
13354b88c807SRodney W. Grimes }
13364bac4483SGarance A Drosehn #undef DIFF_RETURN
13374b88c807SRodney W. Grimes 
13384b88c807SRodney W. Grimes /*
13394b88c807SRodney W. Grimes  * ICK (all for getopt), would rather hide the ugliness
13404b88c807SRodney W. Grimes  * here than taint the main code.
13414b88c807SRodney W. Grimes  *
13424b88c807SRodney W. Grimes  *  ps foo -> ps -foo
13434b88c807SRodney W. Grimes  *  ps 34 -> ps -p34
13444b88c807SRodney W. Grimes  *
13454b88c807SRodney W. Grimes  * The old convention that 't' with no trailing tty arg means the users
13464b88c807SRodney W. Grimes  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
13474b88c807SRodney W. Grimes  * feature is available with the option 'T', which takes no argument.
13484b88c807SRodney W. Grimes  */
13494b88c807SRodney W. Grimes static char *
kludge_oldps_options(const char * optlist,char * origval,const char * nextarg)1350bf46a3bfSGarance A Drosehn kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
13514b88c807SRodney W. Grimes {
13524b88c807SRodney W. Grimes 	size_t len;
1353c675340aSGarance A Drosehn 	char *argp, *cp, *newopts, *ns, *optp, *pidp;
13544b88c807SRodney W. Grimes 
1355daed3ad6SJuli Mallett 	/*
1356c675340aSGarance A Drosehn 	 * See if the original value includes any option which takes an
1357c675340aSGarance A Drosehn 	 * argument (and will thus use up the remainder of the string).
1358daed3ad6SJuli Mallett 	 */
1359c675340aSGarance A Drosehn 	argp = NULL;
1360c675340aSGarance A Drosehn 	if (optlist != NULL) {
1361c675340aSGarance A Drosehn 		for (cp = origval; *cp != '\0'; cp++) {
1362c675340aSGarance A Drosehn 			optp = strchr(optlist, *cp);
1363c675340aSGarance A Drosehn 			if ((optp != NULL) && *(optp + 1) == ':') {
1364c675340aSGarance A Drosehn 				argp = cp;
1365c675340aSGarance A Drosehn 				break;
1366c675340aSGarance A Drosehn 			}
1367c675340aSGarance A Drosehn 		}
1368c675340aSGarance A Drosehn 	}
1369c675340aSGarance A Drosehn 	if (argp != NULL && *origval == '-')
1370c675340aSGarance A Drosehn 		return (origval);
1371daed3ad6SJuli Mallett 
13724b88c807SRodney W. Grimes 	/*
13734b88c807SRodney W. Grimes 	 * if last letter is a 't' flag with no argument (in the context
13744b88c807SRodney W. Grimes 	 * of the oldps options -- option string NOT starting with a '-' --
13754b88c807SRodney W. Grimes 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1376380434d4SBrian Somers 	 *
13772631c777SGarance A Drosehn 	 * However, if a flag accepting a string argument is found earlier
13782631c777SGarance A Drosehn 	 * in the option string (including a possible `t' flag), then the
13792631c777SGarance A Drosehn 	 * remainder of the string must be the argument to that flag; so
1380c675340aSGarance A Drosehn 	 * do not modify that argument.  Note that a trailing `t' would
1381c675340aSGarance A Drosehn 	 * cause argp to be set, if argp was not already set by some
1382c675340aSGarance A Drosehn 	 * earlier option.
13834b88c807SRodney W. Grimes 	 */
1384c675340aSGarance A Drosehn 	len = strlen(origval);
1385c675340aSGarance A Drosehn 	cp = origval + len - 1;
1386c675340aSGarance A Drosehn 	pidp = NULL;
1387bf46a3bfSGarance A Drosehn 	if (*cp == 't' && *origval != '-' && cp == argp) {
1388bf46a3bfSGarance A Drosehn 		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
13894b88c807SRodney W. Grimes 			*cp = 'T';
1390bf46a3bfSGarance A Drosehn 	} else if (argp == NULL) {
1391c675340aSGarance A Drosehn 		/*
1392c675340aSGarance A Drosehn 		 * The original value did not include any option which takes
1393c675340aSGarance A Drosehn 		 * an argument (and that would include `p' and `t'), so check
1394c675340aSGarance A Drosehn 		 * the value for trailing number, or comma-separated list of
1395c675340aSGarance A Drosehn 		 * numbers, which we will treat as a pid request.
1396c675340aSGarance A Drosehn 		 */
1397c675340aSGarance A Drosehn 		if (isdigitch(*cp)) {
1398c675340aSGarance A Drosehn 			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1399c675340aSGarance A Drosehn 				--cp;
1400c675340aSGarance A Drosehn 			pidp = cp + 1;
1401c675340aSGarance A Drosehn 		}
1402c675340aSGarance A Drosehn 	}
1403c675340aSGarance A Drosehn 
1404c675340aSGarance A Drosehn 	/*
1405c675340aSGarance A Drosehn 	 * If nothing needs to be added to the string, then return
1406c675340aSGarance A Drosehn 	 * the "original" (although possibly modified) value.
1407c675340aSGarance A Drosehn 	 */
1408c675340aSGarance A Drosehn 	if (*origval == '-' && pidp == NULL)
1409c675340aSGarance A Drosehn 		return (origval);
1410c675340aSGarance A Drosehn 
1411c675340aSGarance A Drosehn 	/*
1412c675340aSGarance A Drosehn 	 * Create a copy of the string to add '-' and/or 'p' to the
1413c675340aSGarance A Drosehn 	 * original value.
1414c675340aSGarance A Drosehn 	 */
1415c675340aSGarance A Drosehn 	if ((newopts = ns = malloc(len + 3)) == NULL)
14168beb1a2fSMarcel Moolenaar 		xo_errx(1, "malloc failed");
1417c675340aSGarance A Drosehn 
1418c675340aSGarance A Drosehn 	if (*origval != '-')
1419c675340aSGarance A Drosehn 		*ns++ = '-';	/* add option flag */
1420c675340aSGarance A Drosehn 
1421c675340aSGarance A Drosehn 	if (pidp == NULL)
1422c675340aSGarance A Drosehn 		strcpy(ns, origval);
14234b88c807SRodney W. Grimes 	else {
14244b88c807SRodney W. Grimes 		/*
1425c675340aSGarance A Drosehn 		 * Copy everything before the pid string, add the `p',
1426c675340aSGarance A Drosehn 		 * and then copy the pid string.
14274b88c807SRodney W. Grimes 		 */
1428c675340aSGarance A Drosehn 		len = pidp - origval;
1429c675340aSGarance A Drosehn 		memcpy(ns, origval, len);
1430c675340aSGarance A Drosehn 		ns += len;
14314b88c807SRodney W. Grimes 		*ns++ = 'p';
1432c675340aSGarance A Drosehn 		strcpy(ns, pidp);
1433c675340aSGarance A Drosehn 	}
14344b88c807SRodney W. Grimes 
14354b88c807SRodney W. Grimes 	return (newopts);
14364b88c807SRodney W. Grimes }
14374b88c807SRodney W. Grimes 
14384b88c807SRodney W. Grimes static void
pidmax_init(void)143964b0bf0bSPawel Jakub Dawidek pidmax_init(void)
144064b0bf0bSPawel Jakub Dawidek {
144164b0bf0bSPawel Jakub Dawidek 	size_t intsize;
144264b0bf0bSPawel Jakub Dawidek 
144364b0bf0bSPawel Jakub Dawidek 	intsize = sizeof(pid_max);
144464b0bf0bSPawel Jakub Dawidek 	if (sysctlbyname("kern.pid_max", &pid_max, &intsize, NULL, 0) < 0) {
14458beb1a2fSMarcel Moolenaar 		xo_warn("unable to read kern.pid_max");
144664b0bf0bSPawel Jakub Dawidek 		pid_max = 99999;
144764b0bf0bSPawel Jakub Dawidek 	}
144864b0bf0bSPawel Jakub Dawidek }
144964b0bf0bSPawel Jakub Dawidek 
1450c6a5ff71SEitan Adler static void __dead2
usage(void)145146251ddeSWarner Losh usage(void)
14524b88c807SRodney W. Grimes {
145362e6ca0fSKonstantin Belousov #define	SINGLE_OPTS	"[-aCcdeHhjlmrSTuvwXxZ]"
14544b88c807SRodney W. Grimes 
1455e17a2944SYan-Hao Wang 	xo_error("%s\n%s\n%s\n%s\n%s\n",
1456820ac126SMateusz Piotrowski 	    "usage: ps [--libxo] " SINGLE_OPTS " [-O fmt | -o fmt]",
1457820ac126SMateusz Piotrowski 	    "          [-G gid[,gid...]] [-J jid[,jid...]] [-M core] [-N system]",
1458a89237aeSRuslan Ermilov 	    "          [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",
14595c0a1c15SPiotr Pawel Stefaniak 	    "          [-D up | down | both]",
1460820ac126SMateusz Piotrowski 	    "       ps [--libxo] -L");
14614b88c807SRodney W. Grimes 	exit(1);
14624b88c807SRodney W. Grimes }
1463