xref: /freebsd/bin/ps/ps.c (revision 3f0b80bc1537c257f3bd68592832ec8cb65e1c58)
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>
494b88c807SRodney W. Grimes #include <err.h>
504e8b6a6fSGarance A Drosehn #include <errno.h>
514b88c807SRodney W. Grimes #include <fcntl.h>
52a4c8a745SGarance A Drosehn #include <grp.h>
5313767130SBryan Drewery #include <jail.h>
544b88c807SRodney W. Grimes #include <kvm.h>
55b2496d93SMike Pritchard #include <limits.h>
5608017519SAndrey A. Chernov #include <locale.h>
574b88c807SRodney W. Grimes #include <paths.h>
58871e8d8cSMark Murray #include <pwd.h>
594b88c807SRodney W. Grimes #include <stdio.h>
604b88c807SRodney W. Grimes #include <stdlib.h>
614b88c807SRodney W. Grimes #include <string.h>
624b88c807SRodney W. Grimes #include <unistd.h>
638beb1a2fSMarcel Moolenaar #include <libxo/xo.h>
644b88c807SRodney W. Grimes 
654b88c807SRodney W. Grimes #include "ps.h"
664b88c807SRodney W. Grimes 
678a529f59SJohn Baldwin #define	_PATH_PTS	"/dev/pts/"
688a529f59SJohn Baldwin 
69a4c8a745SGarance A Drosehn #define	W_SEP	" \t"		/* "Whitespace" list separators */
70a4c8a745SGarance A Drosehn #define	T_SEP	","		/* "Terminate-element" list separators */
71cf22dcfcSBrian Somers 
72de800cd4SGarance A Drosehn #ifdef LAZY_PS
73c46bb4b3SGarance A Drosehn #define	DEF_UREAD	0
74de800cd4SGarance A Drosehn #define	OPT_LAZY_f	"f"
75de800cd4SGarance A Drosehn #else
76c46bb4b3SGarance A Drosehn #define	DEF_UREAD	1	/* Always do the more-expensive read. */
77de800cd4SGarance A Drosehn #define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
78de800cd4SGarance A Drosehn #endif
794b88c807SRodney W. Grimes 
80c675340aSGarance A Drosehn /*
81ecbb06f8SGarance A Drosehn  * isdigit takes an `int', but expects values in the range of unsigned char.
82ecbb06f8SGarance A Drosehn  * This wrapper ensures that values from a 'char' end up in the correct range.
83c675340aSGarance A Drosehn  */
84ecbb06f8SGarance A Drosehn #define	isdigitch(Anychar) isdigit((u_char)(Anychar))
85c675340aSGarance A Drosehn 
86db91faacSPeter Wemm int	 cflag;			/* -c */
87de800cd4SGarance A Drosehn int	 eval;			/* Exit value */
88de800cd4SGarance A Drosehn time_t	 now;			/* Current time(3) value */
894b88c807SRodney W. Grimes int	 rawcpu;		/* -C */
904b88c807SRodney W. Grimes int	 sumrusage;		/* -S */
91de800cd4SGarance A Drosehn int	 termwidth;		/* Width of the screen (0 == infinity). */
927ab24ea3SJulian Elischer int	 showthreads;		/* will threads be shown? */
934b88c807SRodney W. Grimes 
94bdf8ab46SGarance A Drosehn struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
95de800cd4SGarance A Drosehn 
96de800cd4SGarance A Drosehn static int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
97de800cd4SGarance A Drosehn static kvm_t	*kd;
98de800cd4SGarance A Drosehn static int	 needcomm;	/* -o "command" */
99de800cd4SGarance A Drosehn static int	 needenv;	/* -e */
100de800cd4SGarance A Drosehn static int	 needuser;	/* -o "user" */
101de800cd4SGarance A Drosehn static int	 optfatal;	/* Fatal error parsing some list-option. */
1021818f3fdSBrooks Davis static int	 pid_max;	/* kern.pid_max */
103de800cd4SGarance A Drosehn 
104de800cd4SGarance A Drosehn static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
105ba2cd770SJuli Mallett 
106a4c8a745SGarance A Drosehn struct listinfo;
107de800cd4SGarance A Drosehn typedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
108a4c8a745SGarance A Drosehn 
109a4c8a745SGarance A Drosehn struct listinfo {
110a4c8a745SGarance A Drosehn 	int		 count;
111a4c8a745SGarance A Drosehn 	int		 maxcount;
112a4c8a745SGarance A Drosehn 	int		 elemsize;
113a4c8a745SGarance A Drosehn 	addelem_rtn	*addelem;
114a4c8a745SGarance A Drosehn 	const char	*lname;
115a4c8a745SGarance A Drosehn 	union {
116a4c8a745SGarance A Drosehn 		gid_t	*gids;
11713767130SBryan Drewery 		int	*jids;
118a4c8a745SGarance A Drosehn 		pid_t	*pids;
119a4c8a745SGarance A Drosehn 		dev_t	*ttys;
120a4c8a745SGarance A Drosehn 		uid_t	*uids;
121a4c8a745SGarance A Drosehn 		void	*ptr;
122d822163fSGarance A Drosehn 	} l;
123a4c8a745SGarance A Drosehn };
124a4c8a745SGarance A Drosehn 
125a4c8a745SGarance A Drosehn static int	 addelem_gid(struct listinfo *, const char *);
12613767130SBryan Drewery static int	 addelem_jid(struct listinfo *, const char *);
127a4c8a745SGarance A Drosehn static int	 addelem_pid(struct listinfo *, const char *);
128a4c8a745SGarance A Drosehn static int	 addelem_tty(struct listinfo *, const char *);
129a4c8a745SGarance A Drosehn static int	 addelem_uid(struct listinfo *, const char *);
130a4c8a745SGarance A Drosehn static void	 add_list(struct listinfo *, const char *);
131044fce53SBrian Somers static void	 descendant_sort(KINFO *, int);
1321d1143ecSEdward Tomasz Napierala static void	 format_output(KINFO *);
133a4c8a745SGarance A Drosehn static void	*expand_list(struct listinfo *);
134f35e0715SGarance A Drosehn static const char *
135f35e0715SGarance A Drosehn 		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
1361c67ef12SJohn Baldwin 		    KINFO *, char *, char *, int);
137a4c8a745SGarance A Drosehn static void	 free_list(struct listinfo *);
138a4c8a745SGarance A Drosehn static void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
13925113083SGarance A Drosehn static char	*kludge_oldps_options(const char *, char *, const char *);
1404857f240SGarance A Drosehn static int	 pscomp(const void *, const void *);
1414857f240SGarance A Drosehn static void	 saveuser(KINFO *);
1424857f240SGarance A Drosehn static void	 scanvars(void);
1434857f240SGarance A Drosehn static void	 sizevars(void);
14464b0bf0bSPawel Jakub Dawidek static void	 pidmax_init(void);
1454857f240SGarance A Drosehn static void	 usage(void);
1464b88c807SRodney W. Grimes 
147c0716492SJuli Mallett static char dfmt[] = "pid,tt,state,time,command";
148259fcfacSGarance A Drosehn static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
1491d2324f4SGarance A Drosehn static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
1501d2324f4SGarance A Drosehn 			"tt,time,command";
151871e8d8cSMark Murray static char   o1[] = "pid";
152c0716492SJuli Mallett static char   o2[] = "tt,state,time,command";
153c0716492SJuli Mallett static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
1541d2324f4SGarance A Drosehn static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
1551d2324f4SGarance A Drosehn 			"%cpu,%mem,command";
1562af538ebSRobert Watson static char Zfmt[] = "label";
1574b88c807SRodney W. Grimes 
1585c0a1c15SPiotr Pawel Stefaniak #define	PS_ARGS	"AaCcD:de" OPT_LAZY_f "G:gHhjJ:LlM:mN:O:o:p:rSTt:U:uvwXxZ"
15941623b2dSMaxim Sobolev 
1604b88c807SRodney W. Grimes int
16146251ddeSWarner Losh main(int argc, char *argv[])
1624b88c807SRodney W. Grimes {
16313767130SBryan Drewery 	struct listinfo gidlist, jidlist, pgrplist, pidlist;
164a4c8a745SGarance A Drosehn 	struct listinfo ruidlist, sesslist, ttylist, uidlist;
1654b88c807SRodney W. Grimes 	struct kinfo_proc *kp;
1661d1143ecSEdward Tomasz Napierala 	KINFO *kinfo = NULL, *next_KINFO;
1671d1143ecSEdward Tomasz Napierala 	KINFO_STR *ks;
1684b88c807SRodney W. Grimes 	struct varent *vent;
169484f5781SPedro F. Giffuni 	struct winsize ws = { .ws_row = 0 };
17016eb3576SMarcelo Araujo 	const char *nlistf, *memf, *str;
171ca62e195SGarance A Drosehn 	char *cols;
1721d1143ecSEdward Tomasz Napierala 	int all, ch, elem, flag, _fmt, i, lineno, linelen, left;
173044fce53SBrian Somers 	int descendancy, nentries, nkept, nselectors;
1747ab24ea3SJulian Elischer 	int prtheader, wflag, what, xkeep, xkeep_implied;
1758beb1a2fSMarcel Moolenaar 	int fwidthmin, fwidthmax;
176871e8d8cSMark Murray 	char errbuf[_POSIX2_LINE_MAX];
1778beb1a2fSMarcel Moolenaar 	char fmtbuf[_POSIX2_LINE_MAX];
1785c0a1c15SPiotr Pawel Stefaniak 	enum { NONE = 0, UP = 1, DOWN = 2, BOTH = 1 | 2 } directions = NONE;
1795c0a1c15SPiotr Pawel Stefaniak 	struct { int traversed; int initial; } pid_count;
1804b88c807SRodney W. Grimes 
1812bf4b9cfSAndrey A. Chernov 	(void) setlocale(LC_ALL, "");
182352b6523SGarance A Drosehn 	time(&now);			/* Used by routines in print.c. */
1832bf4b9cfSAndrey A. Chernov 
184b93bb974SMike Karels 	/*
185b93bb974SMike Karels 	 * Compute default output line length before processing options.
186b93bb974SMike Karels 	 * If COLUMNS is set, use it.  Otherwise, if this is part of an
187b93bb974SMike Karels 	 * interactive job (i.e. one associated with a terminal), use
188b93bb974SMike Karels 	 * the terminal width.  "Interactive" is determined by whether
189b93bb974SMike Karels 	 * any of stdout, stderr, or stdin is a terminal.  The intent
190b93bb974SMike Karels 	 * is that "ps", "ps | more", and "ps | grep" all use the same
191b93bb974SMike Karels 	 * default line length unless -w is specified.
19230417f2cSMike Karels 	 *
19330417f2cSMike Karels 	 * If not interactive, the default length was traditionally 79.
19430417f2cSMike Karels 	 * It has been changed to unlimited.  This is mostly for the
19530417f2cSMike Karels 	 * benefit of non-interactive scripts, which arguably should
19630417f2cSMike Karels 	 * use -ww, but is compatible with Linux.
197b93bb974SMike Karels 	 */
1984f18100dSTim J. Robbins 	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
1994f18100dSTim J. Robbins 		termwidth = atoi(cols);
2004f18100dSTim J. Robbins 	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
2014b88c807SRodney W. Grimes 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
2024b88c807SRodney W. Grimes 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
2034b88c807SRodney W. Grimes 	     ws.ws_col == 0)
20430417f2cSMike Karels 		termwidth = UNLIMITED;
2054b88c807SRodney W. Grimes 	else
2064b88c807SRodney W. Grimes 		termwidth = ws.ws_col - 1;
2074b88c807SRodney W. Grimes 
20841623b2dSMaxim Sobolev 	/*
209c675340aSGarance A Drosehn 	 * Hide a number of option-processing kludges in a separate routine,
210c675340aSGarance A Drosehn 	 * to support some historical BSD behaviors, such as `ps axu'.
21141623b2dSMaxim Sobolev 	 */
212c675340aSGarance A Drosehn 	if (argc > 1)
213bf46a3bfSGarance A Drosehn 		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
2144b88c807SRodney W. Grimes 
21564b0bf0bSPawel Jakub Dawidek 	pidmax_init();
21664b0bf0bSPawel Jakub Dawidek 
217044fce53SBrian Somers 	all = descendancy = _fmt = nselectors = optfatal = 0;
218352b6523SGarance A Drosehn 	prtheader = showthreads = wflag = xkeep_implied = 0;
219352b6523SGarance A Drosehn 	xkeep = -1;			/* Neither -x nor -X. */
220a4c8a745SGarance A Drosehn 	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
22113767130SBryan Drewery 	init_list(&jidlist, addelem_jid, sizeof(int), "jail id");
222a4c8a745SGarance A Drosehn 	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
223a4c8a745SGarance A Drosehn 	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
224a4c8a745SGarance A Drosehn 	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
225a4c8a745SGarance A Drosehn 	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
226a4c8a745SGarance A Drosehn 	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
227a4c8a745SGarance A Drosehn 	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
228c08dcaf1SRebecca Cran 	memf = _PATH_DEVNULL;
229c08dcaf1SRebecca Cran 	nlistf = NULL;
2308beb1a2fSMarcel Moolenaar 
2318beb1a2fSMarcel Moolenaar 	argc = xo_parse_args(argc, argv);
2328beb1a2fSMarcel Moolenaar 	if (argc < 0)
2338beb1a2fSMarcel Moolenaar 		exit(1);
2348beb1a2fSMarcel Moolenaar 
23541623b2dSMaxim Sobolev 	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
2360c025af9SKevin Lo 		switch (ch) {
237a4c8a745SGarance A Drosehn 		case 'A':
238a4c8a745SGarance A Drosehn 			/*
239a4c8a745SGarance A Drosehn 			 * Exactly the same as `-ax'.   This has been
240bf2fe08eSUlrich Spörlein 			 * added for compatibility with SUSv3, but for
241a4c8a745SGarance A Drosehn 			 * now it will not be described in the man page.
242a4c8a745SGarance A Drosehn 			 */
243a4c8a745SGarance A Drosehn 			all = xkeep = 1;
244a4c8a745SGarance A Drosehn 			break;
2454b88c807SRodney W. Grimes 		case 'a':
2464b88c807SRodney W. Grimes 			all = 1;
2474b88c807SRodney W. Grimes 			break;
2484b88c807SRodney W. Grimes 		case 'C':
2494b88c807SRodney W. Grimes 			rawcpu = 1;
2504b88c807SRodney W. Grimes 			break;
251db91faacSPeter Wemm 		case 'c':
252db91faacSPeter Wemm 			cflag = 1;
253db91faacSPeter Wemm 			break;
2545c0a1c15SPiotr Pawel Stefaniak 		case 'D': {
2555c0a1c15SPiotr Pawel Stefaniak 				size_t len = strlen(optarg);
2565c0a1c15SPiotr Pawel Stefaniak 
2575c0a1c15SPiotr Pawel Stefaniak 				if (len <= 2 &&
2585c0a1c15SPiotr Pawel Stefaniak 					strncasecmp(optarg, "up", len) == 0)
2595c0a1c15SPiotr Pawel Stefaniak 					directions |= UP;
2605c0a1c15SPiotr Pawel Stefaniak 				else if (len <= 4 &&
2615c0a1c15SPiotr Pawel Stefaniak 					strncasecmp(optarg, "down", len) == 0)
2625c0a1c15SPiotr Pawel Stefaniak 					directions |= DOWN;
2635c0a1c15SPiotr Pawel Stefaniak 				else if (len <= 4 &&
2645c0a1c15SPiotr Pawel Stefaniak 					strncasecmp(optarg, "both", len) == 0)
2655c0a1c15SPiotr Pawel Stefaniak 					directions |= BOTH;
266*3f0b80bcSJamie Landeg-Jones 				else
267*3f0b80bcSJamie Landeg-Jones 					usage();
2685c0a1c15SPiotr Pawel Stefaniak 				break;
2695c0a1c15SPiotr Pawel Stefaniak 			}
270044fce53SBrian Somers 		case 'd':
271044fce53SBrian Somers 			descendancy = 1;
272044fce53SBrian Somers 			break;
273db91faacSPeter Wemm 		case 'e':			/* XXX set ufmt */
274db91faacSPeter Wemm 			needenv = 1;
275db91faacSPeter Wemm 			break;
2764a355d17SGarance A Drosehn #ifdef LAZY_PS
2774a355d17SGarance A Drosehn 		case 'f':
2784a355d17SGarance A Drosehn 			if (getuid() == 0 || getgid() == 0)
2794a355d17SGarance A Drosehn 				forceuread = 1;
2804a355d17SGarance A Drosehn 			break;
2814a355d17SGarance A Drosehn #endif
282a4c8a745SGarance A Drosehn 		case 'G':
283a4c8a745SGarance A Drosehn 			add_list(&gidlist, optarg);
284a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
285a4c8a745SGarance A Drosehn 			nselectors++;
286a4c8a745SGarance A Drosehn 			break;
2874b88c807SRodney W. Grimes 		case 'g':
288352b6523SGarance A Drosehn #if 0
289ba50b0e0SGarance A Drosehn 			/*-
290352b6523SGarance A Drosehn 			 * XXX - This SUSv3 behavior is still under debate
291352b6523SGarance A Drosehn 			 *	since it conflicts with the (undocumented)
292352b6523SGarance A Drosehn 			 *	`-g' option.  So we skip it for now.
293352b6523SGarance A Drosehn 			 */
294a4c8a745SGarance A Drosehn 			add_list(&pgrplist, optarg);
295a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
296a4c8a745SGarance A Drosehn 			nselectors++;
297a4c8a745SGarance A Drosehn 			break;
298a4c8a745SGarance A Drosehn #else
299352b6523SGarance A Drosehn 			/* The historical BSD-ish (from SunOS) behavior. */
3004b88c807SRodney W. Grimes 			break;			/* no-op */
301a4c8a745SGarance A Drosehn #endif
30248b8c0deSScott Long 		case 'H':
303d75c1d83SDaniel Eischen 			showthreads = KERN_PROC_INC_THREAD;
30448b8c0deSScott Long 			break;
3054b88c807SRodney W. Grimes 		case 'h':
3064b88c807SRodney W. Grimes 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
3074b88c807SRodney W. Grimes 			break;
30813767130SBryan Drewery 		case 'J':
30913767130SBryan Drewery 			add_list(&jidlist, optarg);
31013767130SBryan Drewery 			xkeep_implied = 1;
31113767130SBryan Drewery 			nselectors++;
31213767130SBryan Drewery 			break;
3134b88c807SRodney W. Grimes 		case 'j':
314fde411d5SJuli Mallett 			parsefmt(jfmt, 0);
315871e8d8cSMark Murray 			_fmt = 1;
3164b88c807SRodney W. Grimes 			jfmt[0] = '\0';
3174b88c807SRodney W. Grimes 			break;
3184b88c807SRodney W. Grimes 		case 'L':
3194b88c807SRodney W. Grimes 			showkey();
3204b88c807SRodney W. Grimes 			exit(0);
3214b88c807SRodney W. Grimes 		case 'l':
322fde411d5SJuli Mallett 			parsefmt(lfmt, 0);
323871e8d8cSMark Murray 			_fmt = 1;
3244b88c807SRodney W. Grimes 			lfmt[0] = '\0';
3254b88c807SRodney W. Grimes 			break;
3264b88c807SRodney W. Grimes 		case 'M':
3274b88c807SRodney W. Grimes 			memf = optarg;
3284b88c807SRodney W. Grimes 			break;
3294b88c807SRodney W. Grimes 		case 'm':
3304b88c807SRodney W. Grimes 			sortby = SORTMEM;
3314b88c807SRodney W. Grimes 			break;
3324b88c807SRodney W. Grimes 		case 'N':
3334b88c807SRodney W. Grimes 			nlistf = optarg;
3344b88c807SRodney W. Grimes 			break;
3354b88c807SRodney W. Grimes 		case 'O':
336fde411d5SJuli Mallett 			parsefmt(o1, 1);
337fde411d5SJuli Mallett 			parsefmt(optarg, 1);
338fde411d5SJuli Mallett 			parsefmt(o2, 1);
3394b88c807SRodney W. Grimes 			o1[0] = o2[0] = '\0';
340871e8d8cSMark Murray 			_fmt = 1;
3414b88c807SRodney W. Grimes 			break;
3424b88c807SRodney W. Grimes 		case 'o':
343fde411d5SJuli Mallett 			parsefmt(optarg, 1);
344871e8d8cSMark Murray 			_fmt = 1;
3454b88c807SRodney W. Grimes 			break;
3464b88c807SRodney W. Grimes 		case 'p':
347a4c8a745SGarance A Drosehn 			add_list(&pidlist, optarg);
348a4c8a745SGarance A Drosehn 			/*
349a4c8a745SGarance A Drosehn 			 * Note: `-p' does not *set* xkeep, but any values
350a4c8a745SGarance A Drosehn 			 * from pidlist are checked before xkeep is.  That
351a4c8a745SGarance A Drosehn 			 * way they are always matched, even if the user
352a4c8a745SGarance A Drosehn 			 * specifies `-X'.
353a4c8a745SGarance A Drosehn 			 */
354a4c8a745SGarance A Drosehn 			nselectors++;
3554b88c807SRodney W. Grimes 			break;
356a4c8a745SGarance A Drosehn #if 0
357a4c8a745SGarance A Drosehn 		case 'R':
358ba50b0e0SGarance A Drosehn 			/*-
359352b6523SGarance A Drosehn 			 * XXX - This un-standard option is still under
360352b6523SGarance A Drosehn 			 *	debate.  This is what SUSv3 defines as
361352b6523SGarance A Drosehn 			 *	the `-U' option, and while it would be
362352b6523SGarance A Drosehn 			 *	nice to have, it could cause even more
363352b6523SGarance A Drosehn 			 *	confusion to implement it as `-R'.
364352b6523SGarance A Drosehn 			 */
365a4c8a745SGarance A Drosehn 			add_list(&ruidlist, optarg);
366a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
367a4c8a745SGarance A Drosehn 			nselectors++;
368a4c8a745SGarance A Drosehn 			break;
369a4c8a745SGarance A Drosehn #endif
3704b88c807SRodney W. Grimes 		case 'r':
3714b88c807SRodney W. Grimes 			sortby = SORTCPU;
3724b88c807SRodney W. Grimes 			break;
3734b88c807SRodney W. Grimes 		case 'S':
3744b88c807SRodney W. Grimes 			sumrusage = 1;
3754b88c807SRodney W. Grimes 			break;
376a4c8a745SGarance A Drosehn #if 0
377a4c8a745SGarance A Drosehn 		case 's':
378ba50b0e0SGarance A Drosehn 			/*-
379352b6523SGarance A Drosehn 			 * XXX - This non-standard option is still under
380352b6523SGarance A Drosehn 			 *	debate.  This *is* supported on Solaris,
381352b6523SGarance A Drosehn 			 *	Linux, and IRIX, but conflicts with `-s'
382352b6523SGarance A Drosehn 			 *	on NetBSD and maybe some older BSD's.
383352b6523SGarance A Drosehn 			 */
384a4c8a745SGarance A Drosehn 			add_list(&sesslist, optarg);
385a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
386a4c8a745SGarance A Drosehn 			nselectors++;
387a4c8a745SGarance A Drosehn 			break;
388a4c8a745SGarance A Drosehn #endif
3894b88c807SRodney W. Grimes 		case 'T':
3904b88c807SRodney W. Grimes 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
3918beb1a2fSMarcel Moolenaar 				xo_errx(1, "stdin: not a terminal");
3924b88c807SRodney W. Grimes 			/* FALLTHROUGH */
393a4c8a745SGarance A Drosehn 		case 't':
394a4c8a745SGarance A Drosehn 			add_list(&ttylist, optarg);
395a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
396a4c8a745SGarance A Drosehn 			nselectors++;
3974b88c807SRodney W. Grimes 			break;
39873eb8310SPeter Wemm 		case 'U':
399a4c8a745SGarance A Drosehn 			/* This is what SUSv3 defines as the `-u' option. */
400a4c8a745SGarance A Drosehn 			add_list(&uidlist, optarg);
401a4c8a745SGarance A Drosehn 			xkeep_implied = 1;
402a4c8a745SGarance A Drosehn 			nselectors++;
40373eb8310SPeter Wemm 			break;
4044b88c807SRodney W. Grimes 		case 'u':
405fde411d5SJuli Mallett 			parsefmt(ufmt, 0);
4064b88c807SRodney W. Grimes 			sortby = SORTCPU;
407871e8d8cSMark Murray 			_fmt = 1;
4084b88c807SRodney W. Grimes 			ufmt[0] = '\0';
4094b88c807SRodney W. Grimes 			break;
4104b88c807SRodney W. Grimes 		case 'v':
411fde411d5SJuli Mallett 			parsefmt(vfmt, 0);
4124b88c807SRodney W. Grimes 			sortby = SORTMEM;
413871e8d8cSMark Murray 			_fmt = 1;
4144b88c807SRodney W. Grimes 			vfmt[0] = '\0';
4154b88c807SRodney W. Grimes 			break;
4164b88c807SRodney W. Grimes 		case 'w':
4174b88c807SRodney W. Grimes 			if (wflag)
4184b88c807SRodney W. Grimes 				termwidth = UNLIMITED;
419ef1d40daSConrad Meyer 			else if (termwidth < 131 && termwidth != UNLIMITED)
4204b88c807SRodney W. Grimes 				termwidth = 131;
4214b88c807SRodney W. Grimes 			wflag++;
4224b88c807SRodney W. Grimes 			break;
423a4c8a745SGarance A Drosehn 		case 'X':
424a4c8a745SGarance A Drosehn 			/*
425a4c8a745SGarance A Drosehn 			 * Note that `-X' and `-x' are not standard "selector"
426a4c8a745SGarance A Drosehn 			 * options. For most selector-options, we check *all*
427a4c8a745SGarance A Drosehn 			 * processes to see if any are matched by the given
428a4c8a745SGarance A Drosehn 			 * value(s).  After we have a set of all the matched
429a4c8a745SGarance A Drosehn 			 * processes, then `-X' and `-x' govern whether we
430a4c8a745SGarance A Drosehn 			 * modify that *matched* set for processes which do
431a4c8a745SGarance A Drosehn 			 * not have a controlling terminal.  `-X' causes
432a4c8a745SGarance A Drosehn 			 * those processes to be deleted from the matched
433a4c8a745SGarance A Drosehn 			 * set, while `-x' causes them to be kept.
434a4c8a745SGarance A Drosehn 			 */
435a4c8a745SGarance A Drosehn 			xkeep = 0;
436a4c8a745SGarance A Drosehn 			break;
4374b88c807SRodney W. Grimes 		case 'x':
438a4c8a745SGarance A Drosehn 			xkeep = 1;
4394b88c807SRodney W. Grimes 			break;
4407304f61fSBrian Feldman 		case 'Z':
441fde411d5SJuli Mallett 			parsefmt(Zfmt, 0);
4427304f61fSBrian Feldman 			Zfmt[0] = '\0';
4437304f61fSBrian Feldman 			break;
4444b88c807SRodney W. Grimes 		case '?':
4454b88c807SRodney W. Grimes 		default:
4464b88c807SRodney W. Grimes 			usage();
4474b88c807SRodney W. Grimes 		}
4484b88c807SRodney W. Grimes 	argc -= optind;
4494b88c807SRodney W. Grimes 	argv += optind;
450c675340aSGarance A Drosehn 
451c675340aSGarance A Drosehn 	/*
452c675340aSGarance A Drosehn 	 * If there arguments after processing all the options, attempt
453c675340aSGarance A Drosehn 	 * to treat them as a list of process ids.
454c675340aSGarance A Drosehn 	 */
455c675340aSGarance A Drosehn 	while (*argv) {
456c675340aSGarance A Drosehn 		if (!isdigitch(**argv))
457c675340aSGarance A Drosehn 			break;
458c675340aSGarance A Drosehn 		add_list(&pidlist, *argv);
459c675340aSGarance A Drosehn 		argv++;
460c675340aSGarance A Drosehn 	}
461c675340aSGarance A Drosehn 	if (*argv) {
4628beb1a2fSMarcel Moolenaar 		xo_warnx("illegal argument: %s\n", *argv);
463c675340aSGarance A Drosehn 		usage();
464c675340aSGarance A Drosehn 	}
465a4c8a745SGarance A Drosehn 	if (optfatal)
466352b6523SGarance A Drosehn 		exit(1);		/* Error messages already printed. */
467352b6523SGarance A Drosehn 	if (xkeep < 0)			/* Neither -X nor -x was specified. */
468a4c8a745SGarance A Drosehn 		xkeep = xkeep_implied;
469a4c8a745SGarance A Drosehn 
470831c910aSRuslan Ermilov 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
471ec23a763SMarcelo Araujo 	if (kd == NULL)
4728beb1a2fSMarcel Moolenaar 		xo_errx(1, "%s", errbuf);
4734b88c807SRodney W. Grimes 
474871e8d8cSMark Murray 	if (!_fmt)
475fde411d5SJuli Mallett 		parsefmt(dfmt, 0);
4764b88c807SRodney W. Grimes 
477bf27a225SMath Ieu 	if (!all && nselectors == 0) {
478d822163fSGarance A Drosehn 		uidlist.l.ptr = malloc(sizeof(uid_t));
479d822163fSGarance A Drosehn 		if (uidlist.l.ptr == NULL)
4808beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
481a4c8a745SGarance A Drosehn 		nselectors = 1;
482a4c8a745SGarance A Drosehn 		uidlist.count = uidlist.maxcount = 1;
483d822163fSGarance A Drosehn 		*uidlist.l.uids = getuid();
484cf22dcfcSBrian Somers 	}
4854b88c807SRodney W. Grimes 
4864b88c807SRodney W. Grimes 	/*
4874b88c807SRodney W. Grimes 	 * scan requested variables, noting what structures are needed,
488bdfebd84SKris Kennaway 	 * and adjusting header widths as appropriate.
4894b88c807SRodney W. Grimes 	 */
4904b88c807SRodney W. Grimes 	scanvars();
491a4c8a745SGarance A Drosehn 
4924b88c807SRodney W. Grimes 	/*
493a4c8a745SGarance A Drosehn 	 * Get process list.  If the user requested just one selector-
494a4c8a745SGarance A Drosehn 	 * option, then kvm_getprocs can be asked to return just those
495a4c8a745SGarance A Drosehn 	 * processes.  Otherwise, have it return all processes, and
496a4c8a745SGarance A Drosehn 	 * then this routine will search that full list and select the
497a4c8a745SGarance A Drosehn 	 * processes which match any of the user's selector-options.
4984b88c807SRodney W. Grimes 	 */
499d75c1d83SDaniel Eischen 	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
50048b8c0deSScott Long 	flag = 0;
501a4c8a745SGarance A Drosehn 	if (nselectors == 1) {
5027bd42165SGarance A Drosehn 		if (gidlist.count == 1) {
5037bd42165SGarance A Drosehn 			what = KERN_PROC_RGID | showthreads;
5047bd42165SGarance A Drosehn 			flag = *gidlist.l.gids;
5057bd42165SGarance A Drosehn 			nselectors = 0;
5067bd42165SGarance A Drosehn 		} else if (pgrplist.count == 1) {
507a4c8a745SGarance A Drosehn 			what = KERN_PROC_PGRP | showthreads;
508d822163fSGarance A Drosehn 			flag = *pgrplist.l.pids;
509a4c8a745SGarance A Drosehn 			nselectors = 0;
5105c0a1c15SPiotr Pawel Stefaniak 		} else if (pidlist.count == 1 && directions == NONE) {
511a4c8a745SGarance A Drosehn 			what = KERN_PROC_PID | showthreads;
512d822163fSGarance A Drosehn 			flag = *pidlist.l.pids;
513a4c8a745SGarance A Drosehn 			nselectors = 0;
514a4c8a745SGarance A Drosehn 		} else if (ruidlist.count == 1) {
515a4c8a745SGarance A Drosehn 			what = KERN_PROC_RUID | showthreads;
516d822163fSGarance A Drosehn 			flag = *ruidlist.l.uids;
517a4c8a745SGarance A Drosehn 			nselectors = 0;
518a4c8a745SGarance A Drosehn 		} else if (sesslist.count == 1) {
519a4c8a745SGarance A Drosehn 			what = KERN_PROC_SESSION | showthreads;
520d822163fSGarance A Drosehn 			flag = *sesslist.l.pids;
521a4c8a745SGarance A Drosehn 			nselectors = 0;
522a4c8a745SGarance A Drosehn 		} else if (ttylist.count == 1) {
523a4c8a745SGarance A Drosehn 			what = KERN_PROC_TTY | showthreads;
524d822163fSGarance A Drosehn 			flag = *ttylist.l.ttys;
525a4c8a745SGarance A Drosehn 			nselectors = 0;
526a4c8a745SGarance A Drosehn 		} else if (uidlist.count == 1) {
527a4c8a745SGarance A Drosehn 			what = KERN_PROC_UID | showthreads;
528d822163fSGarance A Drosehn 			flag = *uidlist.l.uids;
529a4c8a745SGarance A Drosehn 			nselectors = 0;
530a4c8a745SGarance A Drosehn 		}
5314b88c807SRodney W. Grimes 	}
532d75c1d83SDaniel Eischen 
5334b88c807SRodney W. Grimes 	/*
5344b88c807SRodney W. Grimes 	 * select procs
5354b88c807SRodney W. Grimes 	 */
536a4c8a745SGarance A Drosehn 	nentries = -1;
5374e8b6a6fSGarance A Drosehn 	kp = kvm_getprocs(kd, what, flag, &nentries);
538d7026b96SEdward Tomasz Napierala 	/*
539d7026b96SEdward Tomasz Napierala 	 * Ignore ESRCH to preserve behaviour of "ps -p nonexistent-pid"
540d7026b96SEdward Tomasz Napierala 	 * not reporting an error.
541d7026b96SEdward Tomasz Napierala 	 */
542d7026b96SEdward Tomasz Napierala 	if ((kp == NULL && errno != ESRCH) || (kp != NULL && nentries < 0))
5438beb1a2fSMarcel Moolenaar 		xo_errx(1, "%s", kvm_geterr(kd));
544a4c8a745SGarance A Drosehn 	nkept = 0;
5455c0a1c15SPiotr Pawel Stefaniak 	pid_count.initial = pidlist.count;
5465c0a1c15SPiotr Pawel Stefaniak 	if (directions & DOWN)
5475c0a1c15SPiotr Pawel Stefaniak 		for (elem = 0; elem < pidlist.count; elem++)
5485c0a1c15SPiotr Pawel Stefaniak 			for (i = 0; i < nentries; i++) {
5495c0a1c15SPiotr Pawel Stefaniak 				if (kp[i].ki_ppid == kp[i].ki_pid)
5505c0a1c15SPiotr Pawel Stefaniak 					continue;
5515c0a1c15SPiotr Pawel Stefaniak 				if (kp[i].ki_ppid == pidlist.l.pids[elem]) {
5525c0a1c15SPiotr Pawel Stefaniak 					if (pidlist.count >= pidlist.maxcount)
5535c0a1c15SPiotr Pawel Stefaniak 						expand_list(&pidlist);
5545c0a1c15SPiotr Pawel Stefaniak 					pidlist.l.pids[pidlist.count++] = kp[i].ki_pid;
5555c0a1c15SPiotr Pawel Stefaniak 				}
5565c0a1c15SPiotr Pawel Stefaniak 			}
5575c0a1c15SPiotr Pawel Stefaniak 	pid_count.traversed = pidlist.count;
5585c0a1c15SPiotr Pawel Stefaniak 	if (directions & UP)
5595c0a1c15SPiotr Pawel Stefaniak 		for (elem = 0; elem < pidlist.count; elem++) {
5605c0a1c15SPiotr Pawel Stefaniak 			if (elem >= pid_count.initial && elem < pid_count.traversed)
5615c0a1c15SPiotr Pawel Stefaniak 				continue;
5625c0a1c15SPiotr Pawel Stefaniak 			for (i = 0; i < nentries; i++) {
5635c0a1c15SPiotr Pawel Stefaniak 				if (kp[i].ki_ppid == kp[i].ki_pid)
5645c0a1c15SPiotr Pawel Stefaniak 					continue;
5655c0a1c15SPiotr Pawel Stefaniak 				if (kp[i].ki_pid == pidlist.l.pids[elem]) {
5665c0a1c15SPiotr Pawel Stefaniak 					if (pidlist.count >= pidlist.maxcount)
5675c0a1c15SPiotr Pawel Stefaniak 						expand_list(&pidlist);
5685c0a1c15SPiotr Pawel Stefaniak 					pidlist.l.pids[pidlist.count++] = kp[i].ki_ppid;
5695c0a1c15SPiotr Pawel Stefaniak 				}
5705c0a1c15SPiotr Pawel Stefaniak 			}
5715c0a1c15SPiotr Pawel Stefaniak 		}
5724e8b6a6fSGarance A Drosehn 	if (nentries > 0) {
5734b88c807SRodney W. Grimes 		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
5748beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
5754b88c807SRodney W. Grimes 		for (i = nentries; --i >= 0; ++kp) {
576a4c8a745SGarance A Drosehn 			/*
577a4c8a745SGarance A Drosehn 			 * If the user specified multiple selection-criteria,
578a4c8a745SGarance A Drosehn 			 * then keep any process matched by the inclusive OR
579a4c8a745SGarance A Drosehn 			 * of all the selection-criteria given.
580a4c8a745SGarance A Drosehn 			 */
581a4c8a745SGarance A Drosehn 			if (pidlist.count > 0) {
582a4c8a745SGarance A Drosehn 				for (elem = 0; elem < pidlist.count; elem++)
583d822163fSGarance A Drosehn 					if (kp->ki_pid == pidlist.l.pids[elem])
584a4c8a745SGarance A Drosehn 						goto keepit;
585a4c8a745SGarance A Drosehn 			}
586a4c8a745SGarance A Drosehn 			/*
587a4c8a745SGarance A Drosehn 			 * Note that we had to process pidlist before
588a4c8a745SGarance A Drosehn 			 * filtering out processes which do not have
589a4c8a745SGarance A Drosehn 			 * a controlling terminal.
590a4c8a745SGarance A Drosehn 			 */
591a4c8a745SGarance A Drosehn 			if (xkeep == 0) {
592a4c8a745SGarance A Drosehn 				if ((kp->ki_tdev == NODEV ||
593a4c8a745SGarance A Drosehn 				    (kp->ki_flag & P_CONTROLT) == 0))
594a4c8a745SGarance A Drosehn 					continue;
595a4c8a745SGarance A Drosehn 			}
596a4c8a745SGarance A Drosehn 			if (nselectors == 0)
597a4c8a745SGarance A Drosehn 				goto keepit;
598a4c8a745SGarance A Drosehn 			if (gidlist.count > 0) {
599a4c8a745SGarance A Drosehn 				for (elem = 0; elem < gidlist.count; elem++)
600d822163fSGarance A Drosehn 					if (kp->ki_rgid == gidlist.l.gids[elem])
601a4c8a745SGarance A Drosehn 						goto keepit;
602a4c8a745SGarance A Drosehn 			}
60313767130SBryan Drewery 			if (jidlist.count > 0) {
60413767130SBryan Drewery 				for (elem = 0; elem < jidlist.count; elem++)
60513767130SBryan Drewery 					if (kp->ki_jid == jidlist.l.jids[elem])
60613767130SBryan Drewery 						goto keepit;
60713767130SBryan Drewery 			}
608a4c8a745SGarance A Drosehn 			if (pgrplist.count > 0) {
609a4c8a745SGarance A Drosehn 				for (elem = 0; elem < pgrplist.count; elem++)
610d822163fSGarance A Drosehn 					if (kp->ki_pgid ==
611d822163fSGarance A Drosehn 					    pgrplist.l.pids[elem])
612a4c8a745SGarance A Drosehn 						goto keepit;
613a4c8a745SGarance A Drosehn 			}
614a4c8a745SGarance A Drosehn 			if (ruidlist.count > 0) {
615a4c8a745SGarance A Drosehn 				for (elem = 0; elem < ruidlist.count; elem++)
616d822163fSGarance A Drosehn 					if (kp->ki_ruid ==
617d822163fSGarance A Drosehn 					    ruidlist.l.uids[elem])
618a4c8a745SGarance A Drosehn 						goto keepit;
619a4c8a745SGarance A Drosehn 			}
620a4c8a745SGarance A Drosehn 			if (sesslist.count > 0) {
621a4c8a745SGarance A Drosehn 				for (elem = 0; elem < sesslist.count; elem++)
622d822163fSGarance A Drosehn 					if (kp->ki_sid == sesslist.l.pids[elem])
623a4c8a745SGarance A Drosehn 						goto keepit;
624a4c8a745SGarance A Drosehn 			}
625a4c8a745SGarance A Drosehn 			if (ttylist.count > 0) {
626a4c8a745SGarance A Drosehn 				for (elem = 0; elem < ttylist.count; elem++)
627d822163fSGarance A Drosehn 					if (kp->ki_tdev == ttylist.l.ttys[elem])
628a4c8a745SGarance A Drosehn 						goto keepit;
629a4c8a745SGarance A Drosehn 			}
630a4c8a745SGarance A Drosehn 			if (uidlist.count > 0) {
631a4c8a745SGarance A Drosehn 				for (elem = 0; elem < uidlist.count; elem++)
632d822163fSGarance A Drosehn 					if (kp->ki_uid == uidlist.l.uids[elem])
633a4c8a745SGarance A Drosehn 						goto keepit;
634a4c8a745SGarance A Drosehn 			}
635a4c8a745SGarance A Drosehn 			/*
636a4c8a745SGarance A Drosehn 			 * This process did not match any of the user's
637a4c8a745SGarance A Drosehn 			 * selector-options, so skip the process.
638a4c8a745SGarance A Drosehn 			 */
639a4c8a745SGarance A Drosehn 			continue;
640a4c8a745SGarance A Drosehn 
641a4c8a745SGarance A Drosehn 		keepit:
6424bac4483SGarance A Drosehn 			next_KINFO = &kinfo[nkept];
6434bac4483SGarance A Drosehn 			next_KINFO->ki_p = kp;
644044fce53SBrian Somers 			next_KINFO->ki_d.level = 0;
645044fce53SBrian Somers 			next_KINFO->ki_d.prefix = NULL;
6464bac4483SGarance A Drosehn 			next_KINFO->ki_pcpu = getpcpu(next_KINFO);
6474bac4483SGarance A Drosehn 			if (sortby == SORTMEM)
6484bac4483SGarance A Drosehn 				next_KINFO->ki_memsize = kp->ki_tsize +
6494bac4483SGarance A Drosehn 				    kp->ki_dsize + kp->ki_ssize;
6504b88c807SRodney W. Grimes 			if (needuser)
6514bac4483SGarance A Drosehn 				saveuser(next_KINFO);
652a4c8a745SGarance A Drosehn 			nkept++;
6534b88c807SRodney W. Grimes 		}
6544e8b6a6fSGarance A Drosehn 	}
6556a2d726bSJordan K. Hubbard 
6566a2d726bSJordan K. Hubbard 	sizevars();
6576a2d726bSJordan K. Hubbard 
6581d1143ecSEdward Tomasz Napierala 	if (nkept == 0) {
6594b88c807SRodney W. Grimes 		printheader();
66081fc45fcSKonstantin Belousov 		xo_finish();
661f8c9c11cSWill Andrews 		exit(1);
6621d1143ecSEdward Tomasz Napierala 	}
663a4c8a745SGarance A Drosehn 
6644b88c807SRodney W. Grimes 	/*
6654b88c807SRodney W. Grimes 	 * sort proc list
6664b88c807SRodney W. Grimes 	 */
667a4c8a745SGarance A Drosehn 	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
668044fce53SBrian Somers 
669044fce53SBrian Somers 	/*
670044fce53SBrian Somers 	 * We want things in descendant order
671044fce53SBrian Somers 	 */
672044fce53SBrian Somers 	if (descendancy)
673044fce53SBrian Somers 		descendant_sort(kinfo, nkept);
674044fce53SBrian Somers 
6751d1143ecSEdward Tomasz Napierala 
6764b88c807SRodney W. Grimes 	/*
6771d1143ecSEdward Tomasz Napierala 	 * Prepare formatted output.
6781d1143ecSEdward Tomasz Napierala 	 */
6791d1143ecSEdward Tomasz Napierala 	for (i = 0; i < nkept; i++)
6801d1143ecSEdward Tomasz Napierala 		format_output(&kinfo[i]);
6811d1143ecSEdward Tomasz Napierala 
6821d1143ecSEdward Tomasz Napierala 	/*
6831d1143ecSEdward Tomasz Napierala 	 * Print header.
6841d1143ecSEdward Tomasz Napierala 	 */
6858beb1a2fSMarcel Moolenaar 	xo_open_container("process-information");
6861d1143ecSEdward Tomasz Napierala 	printheader();
6878beb1a2fSMarcel Moolenaar 	if (xo_get_style(NULL) != XO_STYLE_TEXT)
6888beb1a2fSMarcel Moolenaar 		termwidth = UNLIMITED;
6891d1143ecSEdward Tomasz Napierala 
6901d1143ecSEdward Tomasz Napierala 	/*
6911d1143ecSEdward Tomasz Napierala 	 * Output formatted lines.
6924b88c807SRodney W. Grimes 	 */
6938beb1a2fSMarcel Moolenaar 	xo_open_list("process");
694a4c8a745SGarance A Drosehn 	for (i = lineno = 0; i < nkept; i++) {
6951d1143ecSEdward Tomasz Napierala 		linelen = 0;
6968beb1a2fSMarcel Moolenaar 		xo_open_instance("process");
697bdf8ab46SGarance A Drosehn 		STAILQ_FOREACH(vent, &varlist, next_ve) {
6981d1143ecSEdward Tomasz Napierala 			ks = STAILQ_FIRST(&kinfo[i].ki_ks);
6991d1143ecSEdward Tomasz Napierala 			STAILQ_REMOVE_HEAD(&kinfo[i].ki_ks, ks_next);
70038494effSUlrich Spörlein 			/* Truncate rightmost column if necessary.  */
7018beb1a2fSMarcel Moolenaar 			fwidthmax = _POSIX2_LINE_MAX;
7021d1143ecSEdward Tomasz Napierala 			if (STAILQ_NEXT(vent, next_ve) == NULL &&
7031d1143ecSEdward Tomasz Napierala 			   termwidth != UNLIMITED && ks->ks_str != NULL) {
7041d1143ecSEdward Tomasz Napierala 				left = termwidth - linelen;
7051d1143ecSEdward Tomasz Napierala 				if (left > 0 && left < (int)strlen(ks->ks_str))
7068beb1a2fSMarcel Moolenaar 					fwidthmax = left;
7071d1143ecSEdward Tomasz Napierala 			}
7088beb1a2fSMarcel Moolenaar 
7091d1143ecSEdward Tomasz Napierala 			str = ks->ks_str;
7101d1143ecSEdward Tomasz Napierala 			if (str == NULL)
7111d1143ecSEdward Tomasz Napierala 				str = "-";
7121d1143ecSEdward Tomasz Napierala 			/* No padding for the last column, if it's LJUST. */
7138beb1a2fSMarcel Moolenaar 			fwidthmin = (xo_get_style(NULL) != XO_STYLE_TEXT ||
7148beb1a2fSMarcel Moolenaar 			    (STAILQ_NEXT(vent, next_ve) == NULL &&
7158beb1a2fSMarcel Moolenaar 			    (vent->var->flag & LJUST))) ? 0 : vent->var->width;
716aa8ab146SYuri Pankov 			snprintf(fmtbuf, sizeof(fmtbuf), "{:%s/%%%s%d..%dhs}",
717c6a5ff71SEitan Adler 			    vent->var->field ? vent->var->field : vent->var->name,
7188beb1a2fSMarcel Moolenaar 			    (vent->var->flag & LJUST) ? "-" : "",
7198beb1a2fSMarcel Moolenaar 			    fwidthmin, fwidthmax);
7208beb1a2fSMarcel Moolenaar 			xo_emit(fmtbuf, str);
7218beb1a2fSMarcel Moolenaar 			linelen += fwidthmin;
7221d1143ecSEdward Tomasz Napierala 
7231d1143ecSEdward Tomasz Napierala 			if (ks->ks_str != NULL) {
7241d1143ecSEdward Tomasz Napierala 				free(ks->ks_str);
7251d1143ecSEdward Tomasz Napierala 				ks->ks_str = NULL;
7261d1143ecSEdward Tomasz Napierala 			}
7271d1143ecSEdward Tomasz Napierala 			free(ks);
7281d1143ecSEdward Tomasz Napierala 			ks = NULL;
7291d1143ecSEdward Tomasz Napierala 
7301d1143ecSEdward Tomasz Napierala 			if (STAILQ_NEXT(vent, next_ve) != NULL) {
7318beb1a2fSMarcel Moolenaar 				xo_emit("{P: }");
7321d1143ecSEdward Tomasz Napierala 				linelen++;
7331d1143ecSEdward Tomasz Napierala 			}
7344b88c807SRodney W. Grimes 		}
7358beb1a2fSMarcel Moolenaar 	        xo_emit("\n");
7368beb1a2fSMarcel Moolenaar 		xo_close_instance("process");
7374b88c807SRodney W. Grimes 		if (prtheader && lineno++ == prtheader - 4) {
7388beb1a2fSMarcel Moolenaar 			xo_emit("\n");
7394b88c807SRodney W. Grimes 			printheader();
7404b88c807SRodney W. Grimes 			lineno = 0;
7414b88c807SRodney W. Grimes 		}
7424b88c807SRodney W. Grimes 	}
7438beb1a2fSMarcel Moolenaar 	xo_close_list("process");
7448beb1a2fSMarcel Moolenaar 	xo_close_container("process-information");
7458beb1a2fSMarcel Moolenaar 	xo_finish();
7468beb1a2fSMarcel Moolenaar 
747a4c8a745SGarance A Drosehn 	free_list(&gidlist);
74813767130SBryan Drewery 	free_list(&jidlist);
749a4c8a745SGarance A Drosehn 	free_list(&pidlist);
750a4c8a745SGarance A Drosehn 	free_list(&pgrplist);
751a4c8a745SGarance A Drosehn 	free_list(&ruidlist);
752a4c8a745SGarance A Drosehn 	free_list(&sesslist);
753a4c8a745SGarance A Drosehn 	free_list(&ttylist);
754a4c8a745SGarance A Drosehn 	free_list(&uidlist);
755044fce53SBrian Somers 	for (i = 0; i < nkept; i++)
756044fce53SBrian Somers 		free(kinfo[i].ki_d.prefix);
757044fce53SBrian Somers 	free(kinfo);
7582e6c6ac4SGarance A Drosehn 
7594b88c807SRodney W. Grimes 	exit(eval);
7604b88c807SRodney W. Grimes }
7614b88c807SRodney W. Grimes 
762a4c8a745SGarance A Drosehn static int
763a4c8a745SGarance A Drosehn addelem_gid(struct listinfo *inf, const char *elem)
7644e8b6a6fSGarance A Drosehn {
765a4c8a745SGarance A Drosehn 	struct group *grp;
766a4c8a745SGarance A Drosehn 	const char *nameorID;
767a4c8a745SGarance A Drosehn 	char *endp;
7680b42be7cSGarance A Drosehn 	u_long bigtemp;
7694e8b6a6fSGarance A Drosehn 
770a4c8a745SGarance A Drosehn 	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
771a4c8a745SGarance A Drosehn 		if (*elem == '\0')
7728beb1a2fSMarcel Moolenaar 			xo_warnx("Invalid (zero-length) %s name", inf->lname);
773a4c8a745SGarance A Drosehn 		else
7748beb1a2fSMarcel Moolenaar 			xo_warnx("%s name too long: %s", inf->lname, elem);
775a4c8a745SGarance A Drosehn 		optfatal = 1;
776352b6523SGarance A Drosehn 		return (0);		/* Do not add this value. */
7774e8b6a6fSGarance A Drosehn 	}
778a4c8a745SGarance A Drosehn 
7794e8b6a6fSGarance A Drosehn 	/*
780a4c8a745SGarance A Drosehn 	 * SUSv3 states that `ps -G grouplist' should match "real-group
781a4c8a745SGarance A Drosehn 	 * ID numbers", and does not mention group-names.  I do want to
782a4c8a745SGarance A Drosehn 	 * also support group-names, so this tries for a group-id first,
783a4c8a745SGarance A Drosehn 	 * and only tries for a name if that doesn't work.  This is the
784a4c8a745SGarance A Drosehn 	 * opposite order of what is done in addelem_uid(), but in
785a4c8a745SGarance A Drosehn 	 * practice the order would only matter for group-names which
786a4c8a745SGarance A Drosehn 	 * are all-numeric.
7874e8b6a6fSGarance A Drosehn 	 */
788a4c8a745SGarance A Drosehn 	grp = NULL;
789a4c8a745SGarance A Drosehn 	nameorID = "named";
790a4c8a745SGarance A Drosehn 	errno = 0;
7910b42be7cSGarance A Drosehn 	bigtemp = strtoul(elem, &endp, 10);
7920b42be7cSGarance A Drosehn 	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
793a4c8a745SGarance A Drosehn 		nameorID = "name or ID matches";
7940b42be7cSGarance A Drosehn 		grp = getgrgid((gid_t)bigtemp);
795a4c8a745SGarance A Drosehn 	}
796a4c8a745SGarance A Drosehn 	if (grp == NULL)
797a4c8a745SGarance A Drosehn 		grp = getgrnam(elem);
798a4c8a745SGarance A Drosehn 	if (grp == NULL) {
7998beb1a2fSMarcel Moolenaar 		xo_warnx("No %s %s '%s'", inf->lname, nameorID, elem);
800a4c8a745SGarance A Drosehn 		optfatal = 1;
801c23b00b7SGarance A Drosehn 		return (0);
802a4c8a745SGarance A Drosehn 	}
803a4c8a745SGarance A Drosehn 	if (inf->count >= inf->maxcount)
804a4c8a745SGarance A Drosehn 		expand_list(inf);
805d822163fSGarance A Drosehn 	inf->l.gids[(inf->count)++] = grp->gr_gid;
806a4c8a745SGarance A Drosehn 	return (1);
807a4c8a745SGarance A Drosehn }
808a4c8a745SGarance A Drosehn 
809a4c8a745SGarance A Drosehn static int
81013767130SBryan Drewery addelem_jid(struct listinfo *inf, const char *elem)
81113767130SBryan Drewery {
81213767130SBryan Drewery 	int tempid;
81313767130SBryan Drewery 
81413767130SBryan Drewery 	if (*elem == '\0') {
81513767130SBryan Drewery 		warnx("Invalid (zero-length) jail id");
81613767130SBryan Drewery 		optfatal = 1;
81713767130SBryan Drewery 		return (0);		/* Do not add this value. */
81813767130SBryan Drewery 	}
81913767130SBryan Drewery 
82013767130SBryan Drewery 	tempid = jail_getid(elem);
82113767130SBryan Drewery 	if (tempid < 0) {
82213767130SBryan Drewery 		warnx("Invalid %s: %s", inf->lname, elem);
82313767130SBryan Drewery 		optfatal = 1;
82413767130SBryan Drewery 		return (0);
82513767130SBryan Drewery 	}
82613767130SBryan Drewery 
82713767130SBryan Drewery 	if (inf->count >= inf->maxcount)
82813767130SBryan Drewery 		expand_list(inf);
82913767130SBryan Drewery 	inf->l.jids[(inf->count)++] = tempid;
83013767130SBryan Drewery 	return (1);
83113767130SBryan Drewery }
83213767130SBryan Drewery 
83313767130SBryan Drewery static int
834a4c8a745SGarance A Drosehn addelem_pid(struct listinfo *inf, const char *elem)
835a4c8a745SGarance A Drosehn {
836a4c8a745SGarance A Drosehn 	char *endp;
837ca62e195SGarance A Drosehn 	long tempid;
838a4c8a745SGarance A Drosehn 
839de1702f4SGarance A Drosehn 	if (*elem == '\0') {
8408beb1a2fSMarcel Moolenaar 		xo_warnx("Invalid (zero-length) process id");
841de1702f4SGarance A Drosehn 		optfatal = 1;
842de1702f4SGarance A Drosehn 		return (0);		/* Do not add this value. */
84325113083SGarance A Drosehn 	}
84425113083SGarance A Drosehn 
845a4c8a745SGarance A Drosehn 	errno = 0;
846a4c8a745SGarance A Drosehn 	tempid = strtol(elem, &endp, 10);
847a4c8a745SGarance A Drosehn 	if (*endp != '\0' || tempid < 0 || elem == endp) {
8488beb1a2fSMarcel Moolenaar 		xo_warnx("Invalid %s: %s", inf->lname, elem);
8494e8b6a6fSGarance A Drosehn 		errno = ERANGE;
85064b0bf0bSPawel Jakub Dawidek 	} else if (errno != 0 || tempid > pid_max) {
8518beb1a2fSMarcel Moolenaar 		xo_warnx("%s too large: %s", inf->lname, elem);
8524e8b6a6fSGarance A Drosehn 		errno = ERANGE;
8534e8b6a6fSGarance A Drosehn 	}
8544e8b6a6fSGarance A Drosehn 	if (errno == ERANGE) {
855a4c8a745SGarance A Drosehn 		optfatal = 1;
856c23b00b7SGarance A Drosehn 		return (0);
8574e8b6a6fSGarance A Drosehn 	}
858a4c8a745SGarance A Drosehn 	if (inf->count >= inf->maxcount)
859a4c8a745SGarance A Drosehn 		expand_list(inf);
860d822163fSGarance A Drosehn 	inf->l.pids[(inf->count)++] = tempid;
861a4c8a745SGarance A Drosehn 	return (1);
8624e8b6a6fSGarance A Drosehn }
8634e8b6a6fSGarance A Drosehn 
86423b8efadSGarance A Drosehn /*-
86523b8efadSGarance A Drosehn  * The user can specify a device via one of three formats:
8668a529f59SJohn Baldwin  *     1) fully qualified, e.g.:     /dev/ttyp0 /dev/console	/dev/pts/0
8678a529f59SJohn Baldwin  *     2) missing "/dev", e.g.:      ttyp0      console		pts/0
8688a529f59SJohn Baldwin  *     3) two-letters, e.g.:         p0         co		0
86923b8efadSGarance A Drosehn  *        (matching letters that would be seen in the "TT" column)
87023b8efadSGarance A Drosehn  */
871a4c8a745SGarance A Drosehn static int
872a4c8a745SGarance A Drosehn addelem_tty(struct listinfo *inf, const char *elem)
873cf22dcfcSBrian Somers {
874a4c8a745SGarance A Drosehn 	const char *ttypath;
875ca62e195SGarance A Drosehn 	struct stat sb;
8768a529f59SJohn Baldwin 	char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
877a4c8a745SGarance A Drosehn 
87823b8efadSGarance A Drosehn 	ttypath = NULL;
879f2fbfae6SGarance A Drosehn 	pathbuf2[0] = '\0';
8808a529f59SJohn Baldwin 	pathbuf3[0] = '\0';
88123b8efadSGarance A Drosehn 	switch (*elem) {
88223b8efadSGarance A Drosehn 	case '/':
883a4c8a745SGarance A Drosehn 		ttypath = elem;
88423b8efadSGarance A Drosehn 		break;
88523b8efadSGarance A Drosehn 	case 'c':
88623b8efadSGarance A Drosehn 		if (strcmp(elem, "co") == 0) {
88723b8efadSGarance A Drosehn 			ttypath = _PATH_CONSOLE;
88823b8efadSGarance A Drosehn 			break;
88923b8efadSGarance A Drosehn 		}
89023b8efadSGarance A Drosehn 		/* FALLTHROUGH */
89123b8efadSGarance A Drosehn 	default:
89223b8efadSGarance A Drosehn 		strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
893a4c8a745SGarance A Drosehn 		strlcat(pathbuf, elem, sizeof(pathbuf));
894a4c8a745SGarance A Drosehn 		ttypath = pathbuf;
895f2fbfae6SGarance A Drosehn 		if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
89623b8efadSGarance A Drosehn 			break;
8978a529f59SJohn Baldwin 		if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
8988a529f59SJohn Baldwin 			break;
89923b8efadSGarance A Drosehn 		if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
90023b8efadSGarance A Drosehn 			break;
901f2fbfae6SGarance A Drosehn 		/* Check to see if /dev/tty${elem} exists */
902f2fbfae6SGarance A Drosehn 		strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
903f2fbfae6SGarance A Drosehn 		strlcat(pathbuf2, elem, sizeof(pathbuf2));
904f2fbfae6SGarance A Drosehn 		if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
90523b8efadSGarance A Drosehn 			/* No need to repeat stat() && S_ISCHR() checks */
90623b8efadSGarance A Drosehn 			ttypath = NULL;
90723b8efadSGarance A Drosehn 			break;
908a4c8a745SGarance A Drosehn 		}
9098a529f59SJohn Baldwin 		/* Check to see if /dev/pts/${elem} exists */
9108a529f59SJohn Baldwin 		strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
9118a529f59SJohn Baldwin 		strlcat(pathbuf3, elem, sizeof(pathbuf3));
9128a529f59SJohn Baldwin 		if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
9138a529f59SJohn Baldwin 			/* No need to repeat stat() && S_ISCHR() checks */
9148a529f59SJohn Baldwin 			ttypath = NULL;
9158a529f59SJohn Baldwin 			break;
9168a529f59SJohn Baldwin 		}
91723b8efadSGarance A Drosehn 		break;
91823b8efadSGarance A Drosehn 	}
91923b8efadSGarance A Drosehn 	if (ttypath) {
920a4c8a745SGarance A Drosehn 		if (stat(ttypath, &sb) == -1) {
9218a529f59SJohn Baldwin 			if (pathbuf3[0] != '\0')
9228beb1a2fSMarcel Moolenaar 				xo_warn("%s, %s, and %s", pathbuf3, pathbuf2,
9238a529f59SJohn Baldwin 				    ttypath);
924f2fbfae6SGarance A Drosehn 			else
9258beb1a2fSMarcel Moolenaar 				xo_warn("%s", ttypath);
926a4c8a745SGarance A Drosehn 			optfatal = 1;
927c23b00b7SGarance A Drosehn 			return (0);
928a4c8a745SGarance A Drosehn 		}
929a4c8a745SGarance A Drosehn 		if (!S_ISCHR(sb.st_mode)) {
9308a529f59SJohn Baldwin 			if (pathbuf3[0] != '\0')
9318beb1a2fSMarcel Moolenaar 				xo_warnx("%s, %s, and %s: Not a terminal",
9328a529f59SJohn Baldwin 				    pathbuf3, pathbuf2, ttypath);
933f2fbfae6SGarance A Drosehn 			else
9348beb1a2fSMarcel Moolenaar 				xo_warnx("%s: Not a terminal", ttypath);
935a4c8a745SGarance A Drosehn 			optfatal = 1;
936c23b00b7SGarance A Drosehn 			return (0);
937a4c8a745SGarance A Drosehn 		}
93823b8efadSGarance A Drosehn 	}
939a4c8a745SGarance A Drosehn 	if (inf->count >= inf->maxcount)
940a4c8a745SGarance A Drosehn 		expand_list(inf);
941d822163fSGarance A Drosehn 	inf->l.ttys[(inf->count)++] = sb.st_rdev;
942a4c8a745SGarance A Drosehn 	return (1);
943a4c8a745SGarance A Drosehn }
944a4c8a745SGarance A Drosehn 
945a4c8a745SGarance A Drosehn static int
946a4c8a745SGarance A Drosehn addelem_uid(struct listinfo *inf, const char *elem)
947a4c8a745SGarance A Drosehn {
948cf22dcfcSBrian Somers 	struct passwd *pwd;
949a4c8a745SGarance A Drosehn 	char *endp;
9500b42be7cSGarance A Drosehn 	u_long bigtemp;
951cf22dcfcSBrian Somers 
952a4c8a745SGarance A Drosehn 	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
953a4c8a745SGarance A Drosehn 		if (*elem == '\0')
9548beb1a2fSMarcel Moolenaar 			xo_warnx("Invalid (zero-length) %s name", inf->lname);
955a4c8a745SGarance A Drosehn 		else
9568beb1a2fSMarcel Moolenaar 			xo_warnx("%s name too long: %s", inf->lname, elem);
957a4c8a745SGarance A Drosehn 		optfatal = 1;
958352b6523SGarance A Drosehn 		return (0);		/* Do not add this value. */
959a4c8a745SGarance A Drosehn 	}
960cf22dcfcSBrian Somers 
961a4c8a745SGarance A Drosehn 	pwd = getpwnam(elem);
962a4c8a745SGarance A Drosehn 	if (pwd == NULL) {
963a4c8a745SGarance A Drosehn 		errno = 0;
9640b42be7cSGarance A Drosehn 		bigtemp = strtoul(elem, &endp, 10);
9650b42be7cSGarance A Drosehn 		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
9668beb1a2fSMarcel Moolenaar 			xo_warnx("No %s named '%s'", inf->lname, elem);
967a4c8a745SGarance A Drosehn 		else {
968a4c8a745SGarance A Drosehn 			/* The string is all digits, so it might be a userID. */
9690b42be7cSGarance A Drosehn 			pwd = getpwuid((uid_t)bigtemp);
970a4c8a745SGarance A Drosehn 			if (pwd == NULL)
9718beb1a2fSMarcel Moolenaar 				xo_warnx("No %s name or ID matches '%s'",
972a4c8a745SGarance A Drosehn 				    inf->lname, elem);
973cf22dcfcSBrian Somers 		}
974cf22dcfcSBrian Somers 	}
975a4c8a745SGarance A Drosehn 	if (pwd == NULL) {
976e3c4e1ddSGarance A Drosehn 		/*
977e3c4e1ddSGarance A Drosehn 		 * These used to be treated as minor warnings (and the
978e3c4e1ddSGarance A Drosehn 		 * option was simply ignored), but now they are fatal
979e3c4e1ddSGarance A Drosehn 		 * errors (and the command will be aborted).
980e3c4e1ddSGarance A Drosehn 		 */
981e3c4e1ddSGarance A Drosehn 		optfatal = 1;
982c23b00b7SGarance A Drosehn 		return (0);
983cf22dcfcSBrian Somers 	}
984a4c8a745SGarance A Drosehn 	if (inf->count >= inf->maxcount)
985a4c8a745SGarance A Drosehn 		expand_list(inf);
986d822163fSGarance A Drosehn 	inf->l.uids[(inf->count)++] = pwd->pw_uid;
987a4c8a745SGarance A Drosehn 	return (1);
988a4c8a745SGarance A Drosehn }
989cf22dcfcSBrian Somers 
990a4c8a745SGarance A Drosehn static void
991a4c8a745SGarance A Drosehn add_list(struct listinfo *inf, const char *argp)
992a4c8a745SGarance A Drosehn {
993a4c8a745SGarance A Drosehn 	const char *savep;
994a4c8a745SGarance A Drosehn 	char *cp, *endp;
995a4c8a745SGarance A Drosehn 	int toolong;
996ca62e195SGarance A Drosehn 	char elemcopy[PATH_MAX];
997a4c8a745SGarance A Drosehn 
99842856668SEd Maste 	if (*argp == '\0')
99942856668SEd Maste 		inf->addelem(inf, argp);
1000a4c8a745SGarance A Drosehn 	while (*argp != '\0') {
1001a4c8a745SGarance A Drosehn 		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
1002a4c8a745SGarance A Drosehn 			argp++;
1003a4c8a745SGarance A Drosehn 		savep = argp;
1004a4c8a745SGarance A Drosehn 		toolong = 0;
1005a4c8a745SGarance A Drosehn 		cp = elemcopy;
1006a4c8a745SGarance A Drosehn 		if (strchr(T_SEP, *argp) == NULL) {
1007a4c8a745SGarance A Drosehn 			endp = elemcopy + sizeof(elemcopy) - 1;
1008a4c8a745SGarance A Drosehn 			while (*argp != '\0' && cp <= endp &&
1009a4c8a745SGarance A Drosehn 			    strchr(W_SEP T_SEP, *argp) == NULL)
1010a4c8a745SGarance A Drosehn 				*cp++ = *argp++;
1011a4c8a745SGarance A Drosehn 			if (cp > endp)
1012a4c8a745SGarance A Drosehn 				toolong = 1;
1013a4c8a745SGarance A Drosehn 		}
1014a4c8a745SGarance A Drosehn 		if (!toolong) {
1015a4c8a745SGarance A Drosehn 			*cp = '\0';
1016352b6523SGarance A Drosehn 			/*
1017a9626fb3SGarance A Drosehn 			 * Add this single element to the given list.
1018352b6523SGarance A Drosehn 			 */
1019a4c8a745SGarance A Drosehn 			inf->addelem(inf, elemcopy);
1020a4c8a745SGarance A Drosehn 		} else {
1021a4c8a745SGarance A Drosehn 			/*
1022a4c8a745SGarance A Drosehn 			 * The string is too long to copy.  Find the end
1023a4c8a745SGarance A Drosehn 			 * of the string to print out the warning message.
1024a4c8a745SGarance A Drosehn 			 */
1025a4c8a745SGarance A Drosehn 			while (*argp != '\0' && strchr(W_SEP T_SEP,
1026a4c8a745SGarance A Drosehn 			    *argp) == NULL)
1027a4c8a745SGarance A Drosehn 				argp++;
10288beb1a2fSMarcel Moolenaar 			xo_warnx("Value too long: %.*s", (int)(argp - savep),
1029a4c8a745SGarance A Drosehn 			    savep);
1030a4c8a745SGarance A Drosehn 			optfatal = 1;
1031a4c8a745SGarance A Drosehn 		}
1032a4c8a745SGarance A Drosehn 		/*
1033a4c8a745SGarance A Drosehn 		 * Skip over any number of trailing whitespace characters,
1034a4c8a745SGarance A Drosehn 		 * but only one (at most) trailing element-terminating
1035a4c8a745SGarance A Drosehn 		 * character.
1036a4c8a745SGarance A Drosehn 		 */
1037a4c8a745SGarance A Drosehn 		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
1038a4c8a745SGarance A Drosehn 			argp++;
1039a4c8a745SGarance A Drosehn 		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
1040a4c8a745SGarance A Drosehn 			argp++;
1041a4c8a745SGarance A Drosehn 			/* Catch case where string ended with a comma. */
1042a4c8a745SGarance A Drosehn 			if (*argp == '\0')
1043a4c8a745SGarance A Drosehn 				inf->addelem(inf, argp);
1044a4c8a745SGarance A Drosehn 		}
1045a4c8a745SGarance A Drosehn 	}
1046a4c8a745SGarance A Drosehn }
1047a4c8a745SGarance A Drosehn 
1048044fce53SBrian Somers static void
1049044fce53SBrian Somers descendant_sort(KINFO *ki, int items)
1050044fce53SBrian Somers {
1051044fce53SBrian Somers 	int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
1052044fce53SBrian Somers 	unsigned char *path;
1053044fce53SBrian Somers 	KINFO kn;
1054044fce53SBrian Somers 
1055044fce53SBrian Somers 	/*
1056044fce53SBrian Somers 	 * First, sort the entries by descendancy, tracking the descendancy
1057044fce53SBrian Somers 	 * depth in the ki_d.level field.
1058044fce53SBrian Somers 	 */
1059044fce53SBrian Somers 	src = 0;
1060044fce53SBrian Somers 	maxlvl = 0;
1061044fce53SBrian Somers 	while (src < items) {
1062044fce53SBrian Somers 		if (ki[src].ki_d.level) {
1063044fce53SBrian Somers 			src++;
1064044fce53SBrian Somers 			continue;
1065044fce53SBrian Somers 		}
1066044fce53SBrian Somers 		for (nsrc = 1; src + nsrc < items; nsrc++)
1067044fce53SBrian Somers 			if (!ki[src + nsrc].ki_d.level)
1068044fce53SBrian Somers 				break;
1069044fce53SBrian Somers 
1070044fce53SBrian Somers 		for (dst = 0; dst < items; dst++) {
1071044fce53SBrian Somers 			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
1072044fce53SBrian Somers 				continue;
1073044fce53SBrian Somers 			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
1074044fce53SBrian Somers 				break;
1075044fce53SBrian Somers 		}
1076044fce53SBrian Somers 
1077044fce53SBrian Somers 		if (dst == items) {
1078044fce53SBrian Somers 			src += nsrc;
1079044fce53SBrian Somers 			continue;
1080044fce53SBrian Somers 		}
1081044fce53SBrian Somers 
1082044fce53SBrian Somers 		for (ndst = 1; dst + ndst < items; ndst++)
1083044fce53SBrian Somers 			if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
1084044fce53SBrian Somers 				break;
1085044fce53SBrian Somers 
1086044fce53SBrian Somers 		for (n = src; n < src + nsrc; n++) {
1087044fce53SBrian Somers 			ki[n].ki_d.level += ki[dst].ki_d.level + 1;
1088044fce53SBrian Somers 			if (maxlvl < ki[n].ki_d.level)
1089044fce53SBrian Somers 				maxlvl = ki[n].ki_d.level;
1090044fce53SBrian Somers 		}
1091044fce53SBrian Somers 
1092044fce53SBrian Somers 		while (nsrc) {
1093044fce53SBrian Somers 			if (src < dst) {
1094044fce53SBrian Somers 				kn = ki[src];
1095044fce53SBrian Somers 				memmove(ki + src, ki + src + 1,
1096044fce53SBrian Somers 				    (dst - src + ndst - 1) * sizeof *ki);
1097044fce53SBrian Somers 				ki[dst + ndst - 1] = kn;
1098044fce53SBrian Somers 				nsrc--;
1099044fce53SBrian Somers 				dst--;
1100044fce53SBrian Somers 				ndst++;
1101044fce53SBrian Somers 			} else if (src != dst + ndst) {
1102044fce53SBrian Somers 				kn = ki[src];
1103044fce53SBrian Somers 				memmove(ki + dst + ndst + 1, ki + dst + ndst,
1104044fce53SBrian Somers 				    (src - dst - ndst) * sizeof *ki);
1105044fce53SBrian Somers 				ki[dst + ndst] = kn;
1106044fce53SBrian Somers 				ndst++;
1107044fce53SBrian Somers 				nsrc--;
1108044fce53SBrian Somers 				src++;
1109044fce53SBrian Somers 			} else {
1110044fce53SBrian Somers 				ndst += nsrc;
1111044fce53SBrian Somers 				src += nsrc;
1112044fce53SBrian Somers 				nsrc = 0;
1113044fce53SBrian Somers 			}
1114044fce53SBrian Somers 		}
1115044fce53SBrian Somers 	}
1116044fce53SBrian Somers 
1117044fce53SBrian Somers 	/*
1118044fce53SBrian Somers 	 * Now populate ki_d.prefix (instead of ki_d.level) with the command
1119044fce53SBrian Somers 	 * prefix used to show descendancies.
1120044fce53SBrian Somers 	 */
11213322d1c0SAlfonso 	path = calloc((maxlvl + 7) / 8, sizeof(unsigned char));
1122044fce53SBrian Somers 	for (src = 0; src < items; src++) {
1123044fce53SBrian Somers 		if ((lvl = ki[src].ki_d.level) == 0) {
1124044fce53SBrian Somers 			ki[src].ki_d.prefix = NULL;
1125044fce53SBrian Somers 			continue;
1126044fce53SBrian Somers 		}
1127044fce53SBrian Somers 		if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
11288beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
1129044fce53SBrian Somers 		for (n = 0; n < lvl - 2; n++) {
1130044fce53SBrian Somers 			ki[src].ki_d.prefix[n * 2] =
1131044fce53SBrian Somers 			    path[n / 8] & 1 << (n % 8) ? '|' : ' ';
1132044fce53SBrian Somers 			ki[src].ki_d.prefix[n * 2 + 1] = ' ';
1133044fce53SBrian Somers 		}
1134044fce53SBrian Somers 		if (n == lvl - 2) {
1135044fce53SBrian Somers 			/* Have I any more siblings? */
1136044fce53SBrian Somers 			for (siblings = 0, dst = src + 1; dst < items; dst++) {
1137044fce53SBrian Somers 				if (ki[dst].ki_d.level > lvl)
1138044fce53SBrian Somers 					continue;
1139044fce53SBrian Somers 				if (ki[dst].ki_d.level == lvl)
1140044fce53SBrian Somers 					siblings = 1;
1141044fce53SBrian Somers 				break;
1142044fce53SBrian Somers 			}
1143044fce53SBrian Somers 			if (siblings)
1144044fce53SBrian Somers 				path[n / 8] |= 1 << (n % 8);
1145044fce53SBrian Somers 			else
1146044fce53SBrian Somers 				path[n / 8] &= ~(1 << (n % 8));
1147044fce53SBrian Somers 			ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1148044fce53SBrian Somers 			ki[src].ki_d.prefix[n * 2 + 1] = '-';
1149044fce53SBrian Somers 			n++;
1150044fce53SBrian Somers 		}
1151044fce53SBrian Somers 		strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1152044fce53SBrian Somers 	}
1153044fce53SBrian Somers 	free(path);
1154044fce53SBrian Somers }
1155044fce53SBrian Somers 
1156a4c8a745SGarance A Drosehn static void *
1157a4c8a745SGarance A Drosehn expand_list(struct listinfo *inf)
1158a4c8a745SGarance A Drosehn {
1159a4c8a745SGarance A Drosehn 	void *newlist;
1160ca62e195SGarance A Drosehn 	int newmax;
1161a4c8a745SGarance A Drosehn 
1162a4c8a745SGarance A Drosehn 	newmax = (inf->maxcount + 1) << 1;
1163d822163fSGarance A Drosehn 	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1164a4c8a745SGarance A Drosehn 	if (newlist == NULL) {
1165d822163fSGarance A Drosehn 		free(inf->l.ptr);
11668beb1a2fSMarcel Moolenaar 		xo_errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1167a4c8a745SGarance A Drosehn 	}
1168a4c8a745SGarance A Drosehn 	inf->maxcount = newmax;
1169d822163fSGarance A Drosehn 	inf->l.ptr = newlist;
1170a4c8a745SGarance A Drosehn 
1171a4c8a745SGarance A Drosehn 	return (newlist);
1172a4c8a745SGarance A Drosehn }
1173a4c8a745SGarance A Drosehn 
1174a4c8a745SGarance A Drosehn static void
1175a4c8a745SGarance A Drosehn free_list(struct listinfo *inf)
1176a4c8a745SGarance A Drosehn {
1177a4c8a745SGarance A Drosehn 
1178a4c8a745SGarance A Drosehn 	inf->count = inf->elemsize = inf->maxcount = 0;
1179d822163fSGarance A Drosehn 	if (inf->l.ptr != NULL)
1180d822163fSGarance A Drosehn 		free(inf->l.ptr);
1181a4c8a745SGarance A Drosehn 	inf->addelem = NULL;
1182a4c8a745SGarance A Drosehn 	inf->lname = NULL;
1183d822163fSGarance A Drosehn 	inf->l.ptr = NULL;
1184a4c8a745SGarance A Drosehn }
1185a4c8a745SGarance A Drosehn 
1186a4c8a745SGarance A Drosehn static void
1187a4c8a745SGarance A Drosehn init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1188a4c8a745SGarance A Drosehn     const char *lname)
1189a4c8a745SGarance A Drosehn {
1190a4c8a745SGarance A Drosehn 
1191a4c8a745SGarance A Drosehn 	inf->count = inf->maxcount = 0;
1192a4c8a745SGarance A Drosehn 	inf->elemsize = elemsize;
1193a4c8a745SGarance A Drosehn 	inf->addelem = artn;
1194a4c8a745SGarance A Drosehn 	inf->lname = lname;
1195d822163fSGarance A Drosehn 	inf->l.ptr = NULL;
1196cf22dcfcSBrian Somers }
1197cf22dcfcSBrian Somers 
1198fde411d5SJuli Mallett VARENT *
1199fde411d5SJuli Mallett find_varentry(VAR *v)
1200fde411d5SJuli Mallett {
1201fde411d5SJuli Mallett 	struct varent *vent;
1202fde411d5SJuli Mallett 
1203bdf8ab46SGarance A Drosehn 	STAILQ_FOREACH(vent, &varlist, next_ve) {
1204fde411d5SJuli Mallett 		if (strcmp(vent->var->name, v->name) == 0)
1205fde411d5SJuli Mallett 			return vent;
1206fde411d5SJuli Mallett 	}
1207fde411d5SJuli Mallett 	return NULL;
1208fde411d5SJuli Mallett }
1209fde411d5SJuli Mallett 
12104b88c807SRodney W. Grimes static void
121146251ddeSWarner Losh scanvars(void)
12124b88c807SRodney W. Grimes {
12134b88c807SRodney W. Grimes 	struct varent *vent;
12144b88c807SRodney W. Grimes 	VAR *v;
12156a2d726bSJordan K. Hubbard 
1216bdf8ab46SGarance A Drosehn 	STAILQ_FOREACH(vent, &varlist, next_ve) {
12176a2d726bSJordan K. Hubbard 		v = vent->var;
12186a2d726bSJordan K. Hubbard 		if (v->flag & USER)
12196a2d726bSJordan K. Hubbard 			needuser = 1;
12206a2d726bSJordan K. Hubbard 		if (v->flag & COMM)
12216a2d726bSJordan K. Hubbard 			needcomm = 1;
12226a2d726bSJordan K. Hubbard 	}
12236a2d726bSJordan K. Hubbard }
12246a2d726bSJordan K. Hubbard 
12256a2d726bSJordan K. Hubbard static void
12261d1143ecSEdward Tomasz Napierala format_output(KINFO *ki)
12276a2d726bSJordan K. Hubbard {
12286a2d726bSJordan K. Hubbard 	struct varent *vent;
12296a2d726bSJordan K. Hubbard 	VAR *v;
12301d1143ecSEdward Tomasz Napierala 	KINFO_STR *ks;
12311d1143ecSEdward Tomasz Napierala 	char *str;
12321d1143ecSEdward Tomasz Napierala 	int len;
12336a2d726bSJordan K. Hubbard 
12341d1143ecSEdward Tomasz Napierala 	STAILQ_INIT(&ki->ki_ks);
1235bdf8ab46SGarance A Drosehn 	STAILQ_FOREACH(vent, &varlist, next_ve) {
12366a2d726bSJordan K. Hubbard 		v = vent->var;
12371d1143ecSEdward Tomasz Napierala 		str = (v->oproc)(ki, vent);
12381d1143ecSEdward Tomasz Napierala 		ks = malloc(sizeof(*ks));
12391d1143ecSEdward Tomasz Napierala 		if (ks == NULL)
12408beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
12411d1143ecSEdward Tomasz Napierala 		ks->ks_str = str;
12421d1143ecSEdward Tomasz Napierala 		STAILQ_INSERT_TAIL(&ki->ki_ks, ks, ks_next);
12431d1143ecSEdward Tomasz Napierala 		if (str != NULL) {
12441d1143ecSEdward Tomasz Napierala 			len = strlen(str);
12451d1143ecSEdward Tomasz Napierala 		} else
12461d1143ecSEdward Tomasz Napierala 			len = 1; /* "-" */
12471d1143ecSEdward Tomasz Napierala 		if (v->width < len)
12481d1143ecSEdward Tomasz Napierala 			v->width = len;
12496a2d726bSJordan K. Hubbard 	}
12506a2d726bSJordan K. Hubbard }
12516a2d726bSJordan K. Hubbard 
12526a2d726bSJordan K. Hubbard static void
125346251ddeSWarner Losh sizevars(void)
12546a2d726bSJordan K. Hubbard {
12556a2d726bSJordan K. Hubbard 	struct varent *vent;
12566a2d726bSJordan K. Hubbard 	VAR *v;
12574b88c807SRodney W. Grimes 	int i;
12584b88c807SRodney W. Grimes 
1259bdf8ab46SGarance A Drosehn 	STAILQ_FOREACH(vent, &varlist, next_ve) {
12604b88c807SRodney W. Grimes 		v = vent->var;
126178b1878aSJuli Mallett 		i = strlen(vent->header);
12624b88c807SRodney W. Grimes 		if (v->width < i)
12634b88c807SRodney W. Grimes 			v->width = i;
12644b88c807SRodney W. Grimes 	}
12654b88c807SRodney W. Grimes }
12664b88c807SRodney W. Grimes 
1267871e8d8cSMark Murray static const char *
126846251ddeSWarner Losh fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
12691c67ef12SJohn Baldwin     char *comm, char *thread, int maxlen)
12704b88c807SRodney W. Grimes {
1271871e8d8cSMark Murray 	const char *s;
12724b88c807SRodney W. Grimes 
12731c67ef12SJohn Baldwin 	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm,
12749f0b6e5eSJohn Baldwin 	    showthreads && ki->ki_p->ki_numthreads > 1 ? thread : NULL, maxlen);
12754b88c807SRodney W. Grimes 	return (s);
12764b88c807SRodney W. Grimes }
12774b88c807SRodney W. Grimes 
1278b61ce5b0SJeff Roberson #define UREADOK(ki)	(forceuread || (ki->ki_p->ki_flag & P_INMEM))
12793ac5e955SJohn Dyson 
12804b88c807SRodney W. Grimes static void
128146251ddeSWarner Losh saveuser(KINFO *ki)
12824b88c807SRodney W. Grimes {
1283c7f893a4SMark Johnston 	char tdname[COMMLEN + 1];
12845912ca59SDon Lewis 	char *argsp;
12854b88c807SRodney W. Grimes 
1286b61ce5b0SJeff Roberson 	if (ki->ki_p->ki_flag & P_INMEM) {
12874b88c807SRodney W. Grimes 		/*
12884b88c807SRodney W. Grimes 		 * The u-area might be swapped out, and we can't get
12894b88c807SRodney W. Grimes 		 * at it because we have a crashdump and no swap.
12904b88c807SRodney W. Grimes 		 * If it's here fill in these fields, otherwise, just
12914b88c807SRodney W. Grimes 		 * leave them 0.
12924b88c807SRodney W. Grimes 		 */
12931f7d2501SKirk McKusick 		ki->ki_valid = 1;
12944b88c807SRodney W. Grimes 	} else
12951f7d2501SKirk McKusick 		ki->ki_valid = 0;
12964b88c807SRodney W. Grimes 	/*
12974b88c807SRodney W. Grimes 	 * save arguments if needed
12984b88c807SRodney W. Grimes 	 */
1299dd693acfSGarance A Drosehn 	if (needcomm) {
1300c7f893a4SMark Johnston 		if (ki->ki_p->ki_stat == SZOMB) {
1301dd693acfSGarance A Drosehn 			ki->ki_args = strdup("<defunct>");
1302c7f893a4SMark Johnston 		} else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL)) {
1303c7f893a4SMark Johnston 			(void)snprintf(tdname, sizeof(tdname), "%s%s",
1304c7f893a4SMark Johnston 			    ki->ki_p->ki_tdname, ki->ki_p->ki_moretdname);
13055912ca59SDon Lewis 			ki->ki_args = fmt(kvm_getargv, ki,
1306c7f893a4SMark Johnston 			    ki->ki_p->ki_comm, tdname, COMMLEN * 2 + 1);
1307c7f893a4SMark Johnston 		} else {
13085912ca59SDon Lewis 			asprintf(&argsp, "(%s)", ki->ki_p->ki_comm);
13095912ca59SDon Lewis 			ki->ki_args = argsp;
13105912ca59SDon Lewis 		}
1311bd6233fdSGarance A Drosehn 		if (ki->ki_args == NULL)
13128beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
13133ac5e955SJohn Dyson 	} else {
13144b88c807SRodney W. Grimes 		ki->ki_args = NULL;
13153ac5e955SJohn Dyson 	}
1316dd693acfSGarance A Drosehn 	if (needenv) {
1317dd693acfSGarance A Drosehn 		if (UREADOK(ki))
13185912ca59SDon Lewis 			ki->ki_env = fmt(kvm_getenvv, ki,
13195912ca59SDon Lewis 			    (char *)NULL, (char *)NULL, 0);
1320dd693acfSGarance A Drosehn 		else
1321dd693acfSGarance A Drosehn 			ki->ki_env = strdup("()");
1322dd693acfSGarance A Drosehn 		if (ki->ki_env == NULL)
13238beb1a2fSMarcel Moolenaar 			xo_errx(1, "malloc failed");
13243ac5e955SJohn Dyson 	} else {
13254b88c807SRodney W. Grimes 		ki->ki_env = NULL;
13264b88c807SRodney W. Grimes 	}
13273ac5e955SJohn Dyson }
13284b88c807SRodney W. Grimes 
13294bac4483SGarance A Drosehn /* A macro used to improve the readability of pscomp(). */
13304bac4483SGarance A Drosehn #define	DIFF_RETURN(a, b, field) do {	\
13314bac4483SGarance A Drosehn 	if ((a)->field != (b)->field)	\
13324bac4483SGarance A Drosehn 		return (((a)->field < (b)->field) ? -1 : 1); 	\
13334bac4483SGarance A Drosehn } while (0)
13344bac4483SGarance A Drosehn 
13354b88c807SRodney W. Grimes static int
133646251ddeSWarner Losh pscomp(const void *a, const void *b)
13374b88c807SRodney W. Grimes {
13385bd7b1f3SGarance A Drosehn 	const KINFO *ka, *kb;
13394b88c807SRodney W. Grimes 
13405bd7b1f3SGarance A Drosehn 	ka = a;
13415bd7b1f3SGarance A Drosehn 	kb = b;
13425bd7b1f3SGarance A Drosehn 	/* SORTCPU and SORTMEM are sorted in descending order. */
13434bac4483SGarance A Drosehn 	if (sortby == SORTCPU)
13444bac4483SGarance A Drosehn 		DIFF_RETURN(kb, ka, ki_pcpu);
13454bac4483SGarance A Drosehn 	if (sortby == SORTMEM)
13464bac4483SGarance A Drosehn 		DIFF_RETURN(kb, ka, ki_memsize);
13475bd7b1f3SGarance A Drosehn 	/*
13485bd7b1f3SGarance A Drosehn 	 * TTY's are sorted in ascending order, except that all NODEV
13495bd7b1f3SGarance A Drosehn 	 * processes come before all processes with a device.
13505bd7b1f3SGarance A Drosehn 	 */
13514bac4483SGarance A Drosehn 	if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
13524bac4483SGarance A Drosehn 		if (ka->ki_p->ki_tdev == NODEV)
13535bd7b1f3SGarance A Drosehn 			return (-1);
13544bac4483SGarance A Drosehn 		if (kb->ki_p->ki_tdev == NODEV)
13555bd7b1f3SGarance A Drosehn 			return (1);
13564bac4483SGarance A Drosehn 		DIFF_RETURN(ka, kb, ki_p->ki_tdev);
13574bac4483SGarance A Drosehn 	}
13584bac4483SGarance A Drosehn 
1359b4b24324SGarance A Drosehn 	/* PID's and TID's (threads) are sorted in ascending order. */
13604bac4483SGarance A Drosehn 	DIFF_RETURN(ka, kb, ki_p->ki_pid);
1361b4b24324SGarance A Drosehn 	DIFF_RETURN(ka, kb, ki_p->ki_tid);
13625bd7b1f3SGarance A Drosehn 	return (0);
13634b88c807SRodney W. Grimes }
13644bac4483SGarance A Drosehn #undef DIFF_RETURN
13654b88c807SRodney W. Grimes 
13664b88c807SRodney W. Grimes /*
13674b88c807SRodney W. Grimes  * ICK (all for getopt), would rather hide the ugliness
13684b88c807SRodney W. Grimes  * here than taint the main code.
13694b88c807SRodney W. Grimes  *
13704b88c807SRodney W. Grimes  *  ps foo -> ps -foo
13714b88c807SRodney W. Grimes  *  ps 34 -> ps -p34
13724b88c807SRodney W. Grimes  *
13734b88c807SRodney W. Grimes  * The old convention that 't' with no trailing tty arg means the users
13744b88c807SRodney W. Grimes  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
13754b88c807SRodney W. Grimes  * feature is available with the option 'T', which takes no argument.
13764b88c807SRodney W. Grimes  */
13774b88c807SRodney W. Grimes static char *
1378bf46a3bfSGarance A Drosehn kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
13794b88c807SRodney W. Grimes {
13804b88c807SRodney W. Grimes 	size_t len;
1381c675340aSGarance A Drosehn 	char *argp, *cp, *newopts, *ns, *optp, *pidp;
13824b88c807SRodney W. Grimes 
1383daed3ad6SJuli Mallett 	/*
1384c675340aSGarance A Drosehn 	 * See if the original value includes any option which takes an
1385c675340aSGarance A Drosehn 	 * argument (and will thus use up the remainder of the string).
1386daed3ad6SJuli Mallett 	 */
1387c675340aSGarance A Drosehn 	argp = NULL;
1388c675340aSGarance A Drosehn 	if (optlist != NULL) {
1389c675340aSGarance A Drosehn 		for (cp = origval; *cp != '\0'; cp++) {
1390c675340aSGarance A Drosehn 			optp = strchr(optlist, *cp);
1391c675340aSGarance A Drosehn 			if ((optp != NULL) && *(optp + 1) == ':') {
1392c675340aSGarance A Drosehn 				argp = cp;
1393c675340aSGarance A Drosehn 				break;
1394c675340aSGarance A Drosehn 			}
1395c675340aSGarance A Drosehn 		}
1396c675340aSGarance A Drosehn 	}
1397c675340aSGarance A Drosehn 	if (argp != NULL && *origval == '-')
1398c675340aSGarance A Drosehn 		return (origval);
1399daed3ad6SJuli Mallett 
14004b88c807SRodney W. Grimes 	/*
14014b88c807SRodney W. Grimes 	 * if last letter is a 't' flag with no argument (in the context
14024b88c807SRodney W. Grimes 	 * of the oldps options -- option string NOT starting with a '-' --
14034b88c807SRodney W. Grimes 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1404380434d4SBrian Somers 	 *
14052631c777SGarance A Drosehn 	 * However, if a flag accepting a string argument is found earlier
14062631c777SGarance A Drosehn 	 * in the option string (including a possible `t' flag), then the
14072631c777SGarance A Drosehn 	 * remainder of the string must be the argument to that flag; so
1408c675340aSGarance A Drosehn 	 * do not modify that argument.  Note that a trailing `t' would
1409c675340aSGarance A Drosehn 	 * cause argp to be set, if argp was not already set by some
1410c675340aSGarance A Drosehn 	 * earlier option.
14114b88c807SRodney W. Grimes 	 */
1412c675340aSGarance A Drosehn 	len = strlen(origval);
1413c675340aSGarance A Drosehn 	cp = origval + len - 1;
1414c675340aSGarance A Drosehn 	pidp = NULL;
1415bf46a3bfSGarance A Drosehn 	if (*cp == 't' && *origval != '-' && cp == argp) {
1416bf46a3bfSGarance A Drosehn 		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
14174b88c807SRodney W. Grimes 			*cp = 'T';
1418bf46a3bfSGarance A Drosehn 	} else if (argp == NULL) {
1419c675340aSGarance A Drosehn 		/*
1420c675340aSGarance A Drosehn 		 * The original value did not include any option which takes
1421c675340aSGarance A Drosehn 		 * an argument (and that would include `p' and `t'), so check
1422c675340aSGarance A Drosehn 		 * the value for trailing number, or comma-separated list of
1423c675340aSGarance A Drosehn 		 * numbers, which we will treat as a pid request.
1424c675340aSGarance A Drosehn 		 */
1425c675340aSGarance A Drosehn 		if (isdigitch(*cp)) {
1426c675340aSGarance A Drosehn 			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1427c675340aSGarance A Drosehn 				--cp;
1428c675340aSGarance A Drosehn 			pidp = cp + 1;
1429c675340aSGarance A Drosehn 		}
1430c675340aSGarance A Drosehn 	}
1431c675340aSGarance A Drosehn 
1432c675340aSGarance A Drosehn 	/*
1433c675340aSGarance A Drosehn 	 * If nothing needs to be added to the string, then return
1434c675340aSGarance A Drosehn 	 * the "original" (although possibly modified) value.
1435c675340aSGarance A Drosehn 	 */
1436c675340aSGarance A Drosehn 	if (*origval == '-' && pidp == NULL)
1437c675340aSGarance A Drosehn 		return (origval);
1438c675340aSGarance A Drosehn 
1439c675340aSGarance A Drosehn 	/*
1440c675340aSGarance A Drosehn 	 * Create a copy of the string to add '-' and/or 'p' to the
1441c675340aSGarance A Drosehn 	 * original value.
1442c675340aSGarance A Drosehn 	 */
1443c675340aSGarance A Drosehn 	if ((newopts = ns = malloc(len + 3)) == NULL)
14448beb1a2fSMarcel Moolenaar 		xo_errx(1, "malloc failed");
1445c675340aSGarance A Drosehn 
1446c675340aSGarance A Drosehn 	if (*origval != '-')
1447c675340aSGarance A Drosehn 		*ns++ = '-';	/* add option flag */
1448c675340aSGarance A Drosehn 
1449c675340aSGarance A Drosehn 	if (pidp == NULL)
1450c675340aSGarance A Drosehn 		strcpy(ns, origval);
14514b88c807SRodney W. Grimes 	else {
14524b88c807SRodney W. Grimes 		/*
1453c675340aSGarance A Drosehn 		 * Copy everything before the pid string, add the `p',
1454c675340aSGarance A Drosehn 		 * and then copy the pid string.
14554b88c807SRodney W. Grimes 		 */
1456c675340aSGarance A Drosehn 		len = pidp - origval;
1457c675340aSGarance A Drosehn 		memcpy(ns, origval, len);
1458c675340aSGarance A Drosehn 		ns += len;
14594b88c807SRodney W. Grimes 		*ns++ = 'p';
1460c675340aSGarance A Drosehn 		strcpy(ns, pidp);
1461c675340aSGarance A Drosehn 	}
14624b88c807SRodney W. Grimes 
14634b88c807SRodney W. Grimes 	return (newopts);
14644b88c807SRodney W. Grimes }
14654b88c807SRodney W. Grimes 
14664b88c807SRodney W. Grimes static void
146764b0bf0bSPawel Jakub Dawidek pidmax_init(void)
146864b0bf0bSPawel Jakub Dawidek {
146964b0bf0bSPawel Jakub Dawidek 	size_t intsize;
147064b0bf0bSPawel Jakub Dawidek 
147164b0bf0bSPawel Jakub Dawidek 	intsize = sizeof(pid_max);
147264b0bf0bSPawel Jakub Dawidek 	if (sysctlbyname("kern.pid_max", &pid_max, &intsize, NULL, 0) < 0) {
14738beb1a2fSMarcel Moolenaar 		xo_warn("unable to read kern.pid_max");
147464b0bf0bSPawel Jakub Dawidek 		pid_max = 99999;
147564b0bf0bSPawel Jakub Dawidek 	}
147664b0bf0bSPawel Jakub Dawidek }
147764b0bf0bSPawel Jakub Dawidek 
1478c6a5ff71SEitan Adler static void __dead2
147946251ddeSWarner Losh usage(void)
14804b88c807SRodney W. Grimes {
1481aa14b5abSBrian Somers #define	SINGLE_OPTS	"[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
14824b88c807SRodney W. Grimes 
14835c0a1c15SPiotr Pawel Stefaniak 	(void)xo_error("%s\n%s\n%s\n%s\n%s\n",
1484820ac126SMateusz Piotrowski 	    "usage: ps [--libxo] " SINGLE_OPTS " [-O fmt | -o fmt]",
1485820ac126SMateusz Piotrowski 	    "          [-G gid[,gid...]] [-J jid[,jid...]] [-M core] [-N system]",
1486a89237aeSRuslan Ermilov 	    "          [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",
14875c0a1c15SPiotr Pawel Stefaniak 	    "          [-D up | down | both]",
1488820ac126SMateusz Piotrowski 	    "       ps [--libxo] -L");
14894b88c807SRodney W. Grimes 	exit(1);
14904b88c807SRodney W. Grimes }
1491