xref: /freebsd/bin/ps/ps.c (revision 397e83df75e0fcd0d3fcb95ae4d794cb7600fc89)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  * ------+---------+---------+-------- + --------+---------+---------+---------*
31  * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
32  * All rights reserved.
33  *
34  * Significant modifications made to bring `ps' options somewhat closer
35  * to the standard for `ps' as described in SingleUnixSpec-v3.
36  * ------+---------+---------+-------- + --------+---------+---------+---------*
37  */
38 
39 #include <sys/param.h>
40 #include <sys/jail.h>
41 #include <sys/proc.h>
42 #include <sys/user.h>
43 #include <sys/stat.h>
44 #include <sys/ioctl.h>
45 #include <sys/sysctl.h>
46 #include <sys/mount.h>
47 
48 #include <ctype.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <grp.h>
53 #include <jail.h>
54 #include <kvm.h>
55 #include <limits.h>
56 #include <locale.h>
57 #include <paths.h>
58 #include <pwd.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63 #include <libxo/xo.h>
64 
65 #include "ps.h"
66 
67 #define	_PATH_PTS	"/dev/pts/"
68 
69 #define	W_SEP	" \t"		/* "Whitespace" list separators */
70 #define	T_SEP	","		/* "Terminate-element" list separators */
71 
72 #ifdef LAZY_PS
73 #define	DEF_UREAD	0
74 #define	OPT_LAZY_f	"f"
75 #else
76 #define	DEF_UREAD	1	/* Always do the more-expensive read. */
77 #define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
78 #endif
79 
80 /*
81  * isdigit takes an `int', but expects values in the range of unsigned char.
82  * This wrapper ensures that values from a 'char' end up in the correct range.
83  */
84 #define	isdigitch(Anychar) isdigit((u_char)(Anychar))
85 
86 int	 cflag;			/* -c */
87 int	 eval;			/* Exit value */
88 time_t	 now;			/* Current time(3) value */
89 int	 rawcpu;		/* -C */
90 int	 sumrusage;		/* -S */
91 int	 termwidth;		/* Width of the screen (0 == infinity). */
92 int	 showthreads;		/* will threads be shown? */
93 
94 struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
95 
96 static int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
97 static kvm_t	*kd;
98 static int	 needcomm;	/* -o "command" */
99 static int	 needenv;	/* -e */
100 static int	 needuser;	/* -o "user" */
101 static int	 optfatal;	/* Fatal error parsing some list-option. */
102 static int	 pid_max;	/* kern.pid_max */
103 
104 static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
105 
106 struct listinfo;
107 typedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
108 
109 struct listinfo {
110 	int		 count;
111 	int		 maxcount;
112 	int		 elemsize;
113 	addelem_rtn	*addelem;
114 	const char	*lname;
115 	union {
116 		gid_t	*gids;
117 		int	*jids;
118 		pid_t	*pids;
119 		dev_t	*ttys;
120 		uid_t	*uids;
121 		void	*ptr;
122 	} l;
123 };
124 
125 static int	 addelem_gid(struct listinfo *, const char *);
126 static int	 addelem_jid(struct listinfo *, const char *);
127 static int	 addelem_pid(struct listinfo *, const char *);
128 static int	 addelem_tty(struct listinfo *, const char *);
129 static int	 addelem_uid(struct listinfo *, const char *);
130 static void	 add_list(struct listinfo *, const char *);
131 static void	 descendant_sort(KINFO *, int);
132 static void	 format_output(KINFO *);
133 static void	*expand_list(struct listinfo *);
134 static const char *
135 		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
136 		    KINFO *, char *, char *, int);
137 static void	 free_list(struct listinfo *);
138 static void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
139 static char	*kludge_oldps_options(const char *, char *, const char *);
140 static int	 pscomp(const void *, const void *);
141 static void	 saveuser(KINFO *);
142 static void	 scanvars(void);
143 static void	 sizevars(void);
144 static void	 pidmax_init(void);
145 static void	 usage(void);
146 
147 static char dfmt[] = "pid,tt,state,time,command";
148 static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
149 static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
150 			"tt,time,command";
151 static char   o1[] = "pid";
152 static char   o2[] = "tt,state,time,command";
153 static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
154 static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
155 			"%cpu,%mem,command";
156 static char Zfmt[] = "label";
157 
158 #define	PS_ARGS	"AaCcD:de" OPT_LAZY_f "G:gHhjJ:LlM:mN:O:o:p:rSTt:U:uvwXxZ"
159 
160 int
161 main(int argc, char *argv[])
162 {
163 	struct listinfo gidlist, jidlist, pgrplist, pidlist;
164 	struct listinfo ruidlist, sesslist, ttylist, uidlist;
165 	struct kinfo_proc *kp;
166 	KINFO *kinfo = NULL, *next_KINFO;
167 	KINFO_STR *ks;
168 	struct varent *vent;
169 	struct winsize ws = { .ws_row = 0 };
170 	const char *nlistf, *memf, *str;
171 	char *cols;
172 	int all, ch, elem, flag, _fmt, i, lineno, linelen, left;
173 	int descendancy, nentries, nkept, nselectors;
174 	int prtheader, wflag, what, xkeep, xkeep_implied;
175 	int fwidthmin, fwidthmax;
176 	char errbuf[_POSIX2_LINE_MAX];
177 	char fmtbuf[_POSIX2_LINE_MAX];
178 	enum { NONE = 0, UP = 1, DOWN = 2, BOTH = 1 | 2 } directions = NONE;
179 	struct { int traversed; int initial; } pid_count;
180 
181 	(void) setlocale(LC_ALL, "");
182 	time(&now);			/* Used by routines in print.c. */
183 
184 	/*
185 	 * Compute default output line length before processing options.
186 	 * If COLUMNS is set, use it.  Otherwise, if this is part of an
187 	 * interactive job (i.e. one associated with a terminal), use
188 	 * the terminal width.  "Interactive" is determined by whether
189 	 * any of stdout, stderr, or stdin is a terminal.  The intent
190 	 * is that "ps", "ps | more", and "ps | grep" all use the same
191 	 * default line length unless -w is specified.
192 	 *
193 	 * If not interactive, the default length was traditionally 79.
194 	 * It has been changed to unlimited.  This is mostly for the
195 	 * benefit of non-interactive scripts, which arguably should
196 	 * use -ww, but is compatible with Linux.
197 	 */
198 	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
199 		termwidth = atoi(cols);
200 	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
201 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
202 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
203 	     ws.ws_col == 0)
204 		termwidth = UNLIMITED;
205 	else
206 		termwidth = ws.ws_col - 1;
207 
208 	/*
209 	 * Hide a number of option-processing kludges in a separate routine,
210 	 * to support some historical BSD behaviors, such as `ps axu'.
211 	 */
212 	if (argc > 1)
213 		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
214 
215 	pidmax_init();
216 
217 	all = descendancy = _fmt = nselectors = optfatal = 0;
218 	prtheader = showthreads = wflag = xkeep_implied = 0;
219 	xkeep = -1;			/* Neither -x nor -X. */
220 	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
221 	init_list(&jidlist, addelem_jid, sizeof(int), "jail id");
222 	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
223 	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
224 	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
225 	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
226 	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
227 	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
228 	memf = _PATH_DEVNULL;
229 	nlistf = NULL;
230 
231 	argc = xo_parse_args(argc, argv);
232 	if (argc < 0)
233 		exit(1);
234 
235 	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
236 		switch (ch) {
237 		case 'A':
238 			/*
239 			 * Exactly the same as `-ax'.   This has been
240 			 * added for compatibility with SUSv3, but for
241 			 * now it will not be described in the man page.
242 			 */
243 			all = xkeep = 1;
244 			break;
245 		case 'a':
246 			all = 1;
247 			break;
248 		case 'C':
249 			rawcpu = 1;
250 			break;
251 		case 'c':
252 			cflag = 1;
253 			break;
254 		case 'D': {
255 				size_t len = strlen(optarg);
256 
257 				if (len <= 2 &&
258 					strncasecmp(optarg, "up", len) == 0)
259 					directions |= UP;
260 				else if (len <= 4 &&
261 					strncasecmp(optarg, "down", len) == 0)
262 					directions |= DOWN;
263 				else if (len <= 4 &&
264 					strncasecmp(optarg, "both", len) == 0)
265 					directions |= BOTH;
266 				else
267 					usage();
268 				break;
269 			}
270 		case 'd':
271 			descendancy = 1;
272 			break;
273 		case 'e':			/* XXX set ufmt */
274 			needenv = 1;
275 			break;
276 #ifdef LAZY_PS
277 		case 'f':
278 			if (getuid() == 0 || getgid() == 0)
279 				forceuread = 1;
280 			break;
281 #endif
282 		case 'G':
283 			add_list(&gidlist, optarg);
284 			xkeep_implied = 1;
285 			nselectors++;
286 			break;
287 		case 'g':
288 #if 0
289 			/*-
290 			 * XXX - This SUSv3 behavior is still under debate
291 			 *	since it conflicts with the (undocumented)
292 			 *	`-g' option.  So we skip it for now.
293 			 */
294 			add_list(&pgrplist, optarg);
295 			xkeep_implied = 1;
296 			nselectors++;
297 			break;
298 #else
299 			/* The historical BSD-ish (from SunOS) behavior. */
300 			break;			/* no-op */
301 #endif
302 		case 'H':
303 			showthreads = KERN_PROC_INC_THREAD;
304 			break;
305 		case 'h':
306 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
307 			break;
308 		case 'J':
309 			add_list(&jidlist, optarg);
310 			xkeep_implied = 1;
311 			nselectors++;
312 			break;
313 		case 'j':
314 			parsefmt(jfmt, 0);
315 			_fmt = 1;
316 			jfmt[0] = '\0';
317 			break;
318 		case 'L':
319 			showkey();
320 			exit(0);
321 		case 'l':
322 			parsefmt(lfmt, 0);
323 			_fmt = 1;
324 			lfmt[0] = '\0';
325 			break;
326 		case 'M':
327 			memf = optarg;
328 			break;
329 		case 'm':
330 			sortby = SORTMEM;
331 			break;
332 		case 'N':
333 			nlistf = optarg;
334 			break;
335 		case 'O':
336 			parsefmt(o1, 1);
337 			parsefmt(optarg, 1);
338 			parsefmt(o2, 1);
339 			o1[0] = o2[0] = '\0';
340 			_fmt = 1;
341 			break;
342 		case 'o':
343 			parsefmt(optarg, 1);
344 			_fmt = 1;
345 			break;
346 		case 'p':
347 			add_list(&pidlist, optarg);
348 			/*
349 			 * Note: `-p' does not *set* xkeep, but any values
350 			 * from pidlist are checked before xkeep is.  That
351 			 * way they are always matched, even if the user
352 			 * specifies `-X'.
353 			 */
354 			nselectors++;
355 			break;
356 #if 0
357 		case 'R':
358 			/*-
359 			 * XXX - This un-standard option is still under
360 			 *	debate.  This is what SUSv3 defines as
361 			 *	the `-U' option, and while it would be
362 			 *	nice to have, it could cause even more
363 			 *	confusion to implement it as `-R'.
364 			 */
365 			add_list(&ruidlist, optarg);
366 			xkeep_implied = 1;
367 			nselectors++;
368 			break;
369 #endif
370 		case 'r':
371 			sortby = SORTCPU;
372 			break;
373 		case 'S':
374 			sumrusage = 1;
375 			break;
376 #if 0
377 		case 's':
378 			/*-
379 			 * XXX - This non-standard option is still under
380 			 *	debate.  This *is* supported on Solaris,
381 			 *	Linux, and IRIX, but conflicts with `-s'
382 			 *	on NetBSD and maybe some older BSD's.
383 			 */
384 			add_list(&sesslist, optarg);
385 			xkeep_implied = 1;
386 			nselectors++;
387 			break;
388 #endif
389 		case 'T':
390 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
391 				xo_errx(1, "stdin: not a terminal");
392 			/* FALLTHROUGH */
393 		case 't':
394 			add_list(&ttylist, optarg);
395 			xkeep_implied = 1;
396 			nselectors++;
397 			break;
398 		case 'U':
399 			/* This is what SUSv3 defines as the `-u' option. */
400 			add_list(&uidlist, optarg);
401 			xkeep_implied = 1;
402 			nselectors++;
403 			break;
404 		case 'u':
405 			parsefmt(ufmt, 0);
406 			sortby = SORTCPU;
407 			_fmt = 1;
408 			ufmt[0] = '\0';
409 			break;
410 		case 'v':
411 			parsefmt(vfmt, 0);
412 			sortby = SORTMEM;
413 			_fmt = 1;
414 			vfmt[0] = '\0';
415 			break;
416 		case 'w':
417 			if (wflag)
418 				termwidth = UNLIMITED;
419 			else if (termwidth < 131 && termwidth != UNLIMITED)
420 				termwidth = 131;
421 			wflag++;
422 			break;
423 		case 'X':
424 			/*
425 			 * Note that `-X' and `-x' are not standard "selector"
426 			 * options. For most selector-options, we check *all*
427 			 * processes to see if any are matched by the given
428 			 * value(s).  After we have a set of all the matched
429 			 * processes, then `-X' and `-x' govern whether we
430 			 * modify that *matched* set for processes which do
431 			 * not have a controlling terminal.  `-X' causes
432 			 * those processes to be deleted from the matched
433 			 * set, while `-x' causes them to be kept.
434 			 */
435 			xkeep = 0;
436 			break;
437 		case 'x':
438 			xkeep = 1;
439 			break;
440 		case 'Z':
441 			parsefmt(Zfmt, 0);
442 			Zfmt[0] = '\0';
443 			break;
444 		case '?':
445 		default:
446 			usage();
447 		}
448 	argc -= optind;
449 	argv += optind;
450 
451 	/*
452 	 * If there arguments after processing all the options, attempt
453 	 * to treat them as a list of process ids.
454 	 */
455 	while (*argv) {
456 		if (!isdigitch(**argv))
457 			break;
458 		add_list(&pidlist, *argv);
459 		argv++;
460 	}
461 	if (*argv) {
462 		xo_warnx("illegal argument: %s\n", *argv);
463 		usage();
464 	}
465 	if (optfatal)
466 		exit(1);		/* Error messages already printed. */
467 	if (xkeep < 0)			/* Neither -X nor -x was specified. */
468 		xkeep = xkeep_implied;
469 
470 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
471 	if (kd == NULL)
472 		xo_errx(1, "%s", errbuf);
473 
474 	if (!_fmt)
475 		parsefmt(dfmt, 0);
476 
477 	if (!all && nselectors == 0) {
478 		uidlist.l.ptr = malloc(sizeof(uid_t));
479 		if (uidlist.l.ptr == NULL)
480 			xo_errx(1, "malloc failed");
481 		nselectors = 1;
482 		uidlist.count = uidlist.maxcount = 1;
483 		*uidlist.l.uids = getuid();
484 	}
485 
486 	/*
487 	 * scan requested variables, noting what structures are needed,
488 	 * and adjusting header widths as appropriate.
489 	 */
490 	scanvars();
491 
492 	/*
493 	 * Get process list.  If the user requested just one selector-
494 	 * option, then kvm_getprocs can be asked to return just those
495 	 * processes.  Otherwise, have it return all processes, and
496 	 * then this routine will search that full list and select the
497 	 * processes which match any of the user's selector-options.
498 	 */
499 	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
500 	flag = 0;
501 	if (nselectors == 1) {
502 		if (gidlist.count == 1) {
503 			what = KERN_PROC_RGID | showthreads;
504 			flag = *gidlist.l.gids;
505 			nselectors = 0;
506 		} else if (pgrplist.count == 1) {
507 			what = KERN_PROC_PGRP | showthreads;
508 			flag = *pgrplist.l.pids;
509 			nselectors = 0;
510 		} else if (pidlist.count == 1 && directions == NONE) {
511 			what = KERN_PROC_PID | showthreads;
512 			flag = *pidlist.l.pids;
513 			nselectors = 0;
514 		} else if (ruidlist.count == 1) {
515 			what = KERN_PROC_RUID | showthreads;
516 			flag = *ruidlist.l.uids;
517 			nselectors = 0;
518 		} else if (sesslist.count == 1) {
519 			what = KERN_PROC_SESSION | showthreads;
520 			flag = *sesslist.l.pids;
521 			nselectors = 0;
522 		} else if (ttylist.count == 1) {
523 			what = KERN_PROC_TTY | showthreads;
524 			flag = *ttylist.l.ttys;
525 			nselectors = 0;
526 		} else if (uidlist.count == 1) {
527 			what = KERN_PROC_UID | showthreads;
528 			flag = *uidlist.l.uids;
529 			nselectors = 0;
530 		}
531 	}
532 
533 	/*
534 	 * select procs
535 	 */
536 	nentries = -1;
537 	kp = kvm_getprocs(kd, what, flag, &nentries);
538 	/*
539 	 * Ignore ESRCH to preserve behaviour of "ps -p nonexistent-pid"
540 	 * not reporting an error.
541 	 */
542 	if ((kp == NULL && errno != ESRCH) || (kp != NULL && nentries < 0))
543 		xo_errx(1, "%s", kvm_geterr(kd));
544 	nkept = 0;
545 	pid_count.initial = pidlist.count;
546 	if (directions & DOWN)
547 		for (elem = 0; elem < pidlist.count; elem++)
548 			for (i = 0; i < nentries; i++) {
549 				if (kp[i].ki_ppid == kp[i].ki_pid)
550 					continue;
551 				if (kp[i].ki_ppid == pidlist.l.pids[elem]) {
552 					if (pidlist.count >= pidlist.maxcount)
553 						expand_list(&pidlist);
554 					pidlist.l.pids[pidlist.count++] = kp[i].ki_pid;
555 				}
556 			}
557 	pid_count.traversed = pidlist.count;
558 	if (directions & UP)
559 		for (elem = 0; elem < pidlist.count; elem++) {
560 			if (elem >= pid_count.initial && elem < pid_count.traversed)
561 				continue;
562 			for (i = 0; i < nentries; i++) {
563 				if (kp[i].ki_ppid == kp[i].ki_pid)
564 					continue;
565 				if (kp[i].ki_pid == pidlist.l.pids[elem]) {
566 					if (pidlist.count >= pidlist.maxcount)
567 						expand_list(&pidlist);
568 					pidlist.l.pids[pidlist.count++] = kp[i].ki_ppid;
569 				}
570 			}
571 		}
572 	if (nentries > 0) {
573 		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
574 			xo_errx(1, "malloc failed");
575 		for (i = nentries; --i >= 0; ++kp) {
576 			/*
577 			 * If the user specified multiple selection-criteria,
578 			 * then keep any process matched by the inclusive OR
579 			 * of all the selection-criteria given.
580 			 */
581 			if (pidlist.count > 0) {
582 				for (elem = 0; elem < pidlist.count; elem++)
583 					if (kp->ki_pid == pidlist.l.pids[elem])
584 						goto keepit;
585 			}
586 			/*
587 			 * Note that we had to process pidlist before
588 			 * filtering out processes which do not have
589 			 * a controlling terminal.
590 			 */
591 			if (xkeep == 0) {
592 				if ((kp->ki_tdev == NODEV ||
593 				    (kp->ki_flag & P_CONTROLT) == 0))
594 					continue;
595 			}
596 			if (nselectors == 0)
597 				goto keepit;
598 			if (gidlist.count > 0) {
599 				for (elem = 0; elem < gidlist.count; elem++)
600 					if (kp->ki_rgid == gidlist.l.gids[elem])
601 						goto keepit;
602 			}
603 			if (jidlist.count > 0) {
604 				for (elem = 0; elem < jidlist.count; elem++)
605 					if (kp->ki_jid == jidlist.l.jids[elem])
606 						goto keepit;
607 			}
608 			if (pgrplist.count > 0) {
609 				for (elem = 0; elem < pgrplist.count; elem++)
610 					if (kp->ki_pgid ==
611 					    pgrplist.l.pids[elem])
612 						goto keepit;
613 			}
614 			if (ruidlist.count > 0) {
615 				for (elem = 0; elem < ruidlist.count; elem++)
616 					if (kp->ki_ruid ==
617 					    ruidlist.l.uids[elem])
618 						goto keepit;
619 			}
620 			if (sesslist.count > 0) {
621 				for (elem = 0; elem < sesslist.count; elem++)
622 					if (kp->ki_sid == sesslist.l.pids[elem])
623 						goto keepit;
624 			}
625 			if (ttylist.count > 0) {
626 				for (elem = 0; elem < ttylist.count; elem++)
627 					if (kp->ki_tdev == ttylist.l.ttys[elem])
628 						goto keepit;
629 			}
630 			if (uidlist.count > 0) {
631 				for (elem = 0; elem < uidlist.count; elem++)
632 					if (kp->ki_uid == uidlist.l.uids[elem])
633 						goto keepit;
634 			}
635 			/*
636 			 * This process did not match any of the user's
637 			 * selector-options, so skip the process.
638 			 */
639 			continue;
640 
641 		keepit:
642 			next_KINFO = &kinfo[nkept];
643 			next_KINFO->ki_p = kp;
644 			next_KINFO->ki_d.level = 0;
645 			next_KINFO->ki_d.prefix = NULL;
646 			next_KINFO->ki_pcpu = getpcpu(next_KINFO);
647 			if (sortby == SORTMEM)
648 				next_KINFO->ki_memsize = kp->ki_tsize +
649 				    kp->ki_dsize + kp->ki_ssize;
650 			if (needuser)
651 				saveuser(next_KINFO);
652 			nkept++;
653 		}
654 	}
655 
656 	sizevars();
657 
658 	if (nkept == 0) {
659 		printheader();
660 		xo_finish();
661 		exit(1);
662 	}
663 
664 	/*
665 	 * sort proc list
666 	 */
667 	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
668 
669 	/*
670 	 * We want things in descendant order
671 	 */
672 	if (descendancy)
673 		descendant_sort(kinfo, nkept);
674 
675 
676 	/*
677 	 * Prepare formatted output.
678 	 */
679 	for (i = 0; i < nkept; i++)
680 		format_output(&kinfo[i]);
681 
682 	/*
683 	 * Print header.
684 	 */
685 	xo_open_container("process-information");
686 	printheader();
687 	if (xo_get_style(NULL) != XO_STYLE_TEXT)
688 		termwidth = UNLIMITED;
689 
690 	/*
691 	 * Output formatted lines.
692 	 */
693 	xo_open_list("process");
694 	for (i = lineno = 0; i < nkept; i++) {
695 		linelen = 0;
696 		xo_open_instance("process");
697 		STAILQ_FOREACH(vent, &varlist, next_ve) {
698 			ks = STAILQ_FIRST(&kinfo[i].ki_ks);
699 			STAILQ_REMOVE_HEAD(&kinfo[i].ki_ks, ks_next);
700 			/* Truncate rightmost column if necessary.  */
701 			fwidthmax = _POSIX2_LINE_MAX;
702 			if (STAILQ_NEXT(vent, next_ve) == NULL &&
703 			   termwidth != UNLIMITED && ks->ks_str != NULL) {
704 				left = termwidth - linelen;
705 				if (left > 0 && left < (int)strlen(ks->ks_str))
706 					fwidthmax = left;
707 			}
708 
709 			str = ks->ks_str;
710 			if (str == NULL)
711 				str = "-";
712 			/* No padding for the last column, if it's LJUST. */
713 			fwidthmin = (xo_get_style(NULL) != XO_STYLE_TEXT ||
714 			    (STAILQ_NEXT(vent, next_ve) == NULL &&
715 			    (vent->var->flag & LJUST))) ? 0 : vent->var->width;
716 			snprintf(fmtbuf, sizeof(fmtbuf), "{:%s/%%%s%d..%dhs}",
717 			    vent->var->field ? vent->var->field : vent->var->name,
718 			    (vent->var->flag & LJUST) ? "-" : "",
719 			    fwidthmin, fwidthmax);
720 			xo_emit(fmtbuf, str);
721 			linelen += fwidthmin;
722 
723 			if (ks->ks_str != NULL) {
724 				free(ks->ks_str);
725 				ks->ks_str = NULL;
726 			}
727 			free(ks);
728 			ks = NULL;
729 
730 			if (STAILQ_NEXT(vent, next_ve) != NULL) {
731 				xo_emit("{P: }");
732 				linelen++;
733 			}
734 		}
735 	        xo_emit("\n");
736 		xo_close_instance("process");
737 		if (prtheader && lineno++ == prtheader - 4) {
738 			xo_emit("\n");
739 			printheader();
740 			lineno = 0;
741 		}
742 	}
743 	xo_close_list("process");
744 	xo_close_container("process-information");
745 	xo_finish();
746 
747 	free_list(&gidlist);
748 	free_list(&jidlist);
749 	free_list(&pidlist);
750 	free_list(&pgrplist);
751 	free_list(&ruidlist);
752 	free_list(&sesslist);
753 	free_list(&ttylist);
754 	free_list(&uidlist);
755 	for (i = 0; i < nkept; i++)
756 		free(kinfo[i].ki_d.prefix);
757 	free(kinfo);
758 
759 	exit(eval);
760 }
761 
762 static int
763 addelem_gid(struct listinfo *inf, const char *elem)
764 {
765 	struct group *grp;
766 	const char *nameorID;
767 	char *endp;
768 	u_long bigtemp;
769 
770 	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
771 		if (*elem == '\0')
772 			xo_warnx("Invalid (zero-length) %s name", inf->lname);
773 		else
774 			xo_warnx("%s name too long: %s", inf->lname, elem);
775 		optfatal = 1;
776 		return (0);		/* Do not add this value. */
777 	}
778 
779 	/*
780 	 * SUSv3 states that `ps -G grouplist' should match "real-group
781 	 * ID numbers", and does not mention group-names.  I do want to
782 	 * also support group-names, so this tries for a group-id first,
783 	 * and only tries for a name if that doesn't work.  This is the
784 	 * opposite order of what is done in addelem_uid(), but in
785 	 * practice the order would only matter for group-names which
786 	 * are all-numeric.
787 	 */
788 	grp = NULL;
789 	nameorID = "named";
790 	errno = 0;
791 	bigtemp = strtoul(elem, &endp, 10);
792 	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
793 		nameorID = "name or ID matches";
794 		grp = getgrgid((gid_t)bigtemp);
795 	}
796 	if (grp == NULL)
797 		grp = getgrnam(elem);
798 	if (grp == NULL) {
799 		xo_warnx("No %s %s '%s'", inf->lname, nameorID, elem);
800 		optfatal = 1;
801 		return (0);
802 	}
803 	if (inf->count >= inf->maxcount)
804 		expand_list(inf);
805 	inf->l.gids[(inf->count)++] = grp->gr_gid;
806 	return (1);
807 }
808 
809 static int
810 addelem_jid(struct listinfo *inf, const char *elem)
811 {
812 	int tempid;
813 
814 	if (*elem == '\0') {
815 		warnx("Invalid (zero-length) jail id");
816 		optfatal = 1;
817 		return (0);		/* Do not add this value. */
818 	}
819 
820 	tempid = jail_getid(elem);
821 	if (tempid < 0) {
822 		warnx("Invalid %s: %s", inf->lname, elem);
823 		optfatal = 1;
824 		return (0);
825 	}
826 
827 	if (inf->count >= inf->maxcount)
828 		expand_list(inf);
829 	inf->l.jids[(inf->count)++] = tempid;
830 	return (1);
831 }
832 
833 static int
834 addelem_pid(struct listinfo *inf, const char *elem)
835 {
836 	char *endp;
837 	long tempid;
838 
839 	if (*elem == '\0') {
840 		xo_warnx("Invalid (zero-length) process id");
841 		optfatal = 1;
842 		return (0);		/* Do not add this value. */
843 	}
844 
845 	errno = 0;
846 	tempid = strtol(elem, &endp, 10);
847 	if (*endp != '\0' || tempid < 0 || elem == endp) {
848 		xo_warnx("Invalid %s: %s", inf->lname, elem);
849 		errno = ERANGE;
850 	} else if (errno != 0 || tempid > pid_max) {
851 		xo_warnx("%s too large: %s", inf->lname, elem);
852 		errno = ERANGE;
853 	}
854 	if (errno == ERANGE) {
855 		optfatal = 1;
856 		return (0);
857 	}
858 	if (inf->count >= inf->maxcount)
859 		expand_list(inf);
860 	inf->l.pids[(inf->count)++] = tempid;
861 	return (1);
862 }
863 
864 /*-
865  * The user can specify a device via one of three formats:
866  *     1) fully qualified, e.g.:     /dev/ttyp0 /dev/console	/dev/pts/0
867  *     2) missing "/dev", e.g.:      ttyp0      console		pts/0
868  *     3) two-letters, e.g.:         p0         co		0
869  *        (matching letters that would be seen in the "TT" column)
870  */
871 static int
872 addelem_tty(struct listinfo *inf, const char *elem)
873 {
874 	const char *ttypath;
875 	struct stat sb;
876 	char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
877 
878 	ttypath = NULL;
879 	pathbuf2[0] = '\0';
880 	pathbuf3[0] = '\0';
881 	switch (*elem) {
882 	case '/':
883 		ttypath = elem;
884 		break;
885 	case 'c':
886 		if (strcmp(elem, "co") == 0) {
887 			ttypath = _PATH_CONSOLE;
888 			break;
889 		}
890 		/* FALLTHROUGH */
891 	default:
892 		strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
893 		strlcat(pathbuf, elem, sizeof(pathbuf));
894 		ttypath = pathbuf;
895 		if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
896 			break;
897 		if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
898 			break;
899 		if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
900 			break;
901 		/* Check to see if /dev/tty${elem} exists */
902 		strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
903 		strlcat(pathbuf2, elem, sizeof(pathbuf2));
904 		if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
905 			/* No need to repeat stat() && S_ISCHR() checks */
906 			ttypath = NULL;
907 			break;
908 		}
909 		/* Check to see if /dev/pts/${elem} exists */
910 		strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
911 		strlcat(pathbuf3, elem, sizeof(pathbuf3));
912 		if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
913 			/* No need to repeat stat() && S_ISCHR() checks */
914 			ttypath = NULL;
915 			break;
916 		}
917 		break;
918 	}
919 	if (ttypath) {
920 		if (stat(ttypath, &sb) == -1) {
921 			if (pathbuf3[0] != '\0')
922 				xo_warn("%s, %s, and %s", pathbuf3, pathbuf2,
923 				    ttypath);
924 			else
925 				xo_warn("%s", ttypath);
926 			optfatal = 1;
927 			return (0);
928 		}
929 		if (!S_ISCHR(sb.st_mode)) {
930 			if (pathbuf3[0] != '\0')
931 				xo_warnx("%s, %s, and %s: Not a terminal",
932 				    pathbuf3, pathbuf2, ttypath);
933 			else
934 				xo_warnx("%s: Not a terminal", ttypath);
935 			optfatal = 1;
936 			return (0);
937 		}
938 	}
939 	if (inf->count >= inf->maxcount)
940 		expand_list(inf);
941 	inf->l.ttys[(inf->count)++] = sb.st_rdev;
942 	return (1);
943 }
944 
945 static int
946 addelem_uid(struct listinfo *inf, const char *elem)
947 {
948 	struct passwd *pwd;
949 	char *endp;
950 	u_long bigtemp;
951 
952 	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
953 		if (*elem == '\0')
954 			xo_warnx("Invalid (zero-length) %s name", inf->lname);
955 		else
956 			xo_warnx("%s name too long: %s", inf->lname, elem);
957 		optfatal = 1;
958 		return (0);		/* Do not add this value. */
959 	}
960 
961 	pwd = getpwnam(elem);
962 	if (pwd == NULL) {
963 		errno = 0;
964 		bigtemp = strtoul(elem, &endp, 10);
965 		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
966 			xo_warnx("No %s named '%s'", inf->lname, elem);
967 		else {
968 			/* The string is all digits, so it might be a userID. */
969 			pwd = getpwuid((uid_t)bigtemp);
970 			if (pwd == NULL)
971 				xo_warnx("No %s name or ID matches '%s'",
972 				    inf->lname, elem);
973 		}
974 	}
975 	if (pwd == NULL) {
976 		/*
977 		 * These used to be treated as minor warnings (and the
978 		 * option was simply ignored), but now they are fatal
979 		 * errors (and the command will be aborted).
980 		 */
981 		optfatal = 1;
982 		return (0);
983 	}
984 	if (inf->count >= inf->maxcount)
985 		expand_list(inf);
986 	inf->l.uids[(inf->count)++] = pwd->pw_uid;
987 	return (1);
988 }
989 
990 static void
991 add_list(struct listinfo *inf, const char *argp)
992 {
993 	const char *savep;
994 	char *cp, *endp;
995 	int toolong;
996 	char elemcopy[PATH_MAX];
997 
998 	if (*argp == '\0')
999 		inf->addelem(inf, argp);
1000 	while (*argp != '\0') {
1001 		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
1002 			argp++;
1003 		savep = argp;
1004 		toolong = 0;
1005 		cp = elemcopy;
1006 		if (strchr(T_SEP, *argp) == NULL) {
1007 			endp = elemcopy + sizeof(elemcopy) - 1;
1008 			while (*argp != '\0' && cp <= endp &&
1009 			    strchr(W_SEP T_SEP, *argp) == NULL)
1010 				*cp++ = *argp++;
1011 			if (cp > endp)
1012 				toolong = 1;
1013 		}
1014 		if (!toolong) {
1015 			*cp = '\0';
1016 			/*
1017 			 * Add this single element to the given list.
1018 			 */
1019 			inf->addelem(inf, elemcopy);
1020 		} else {
1021 			/*
1022 			 * The string is too long to copy.  Find the end
1023 			 * of the string to print out the warning message.
1024 			 */
1025 			while (*argp != '\0' && strchr(W_SEP T_SEP,
1026 			    *argp) == NULL)
1027 				argp++;
1028 			xo_warnx("Value too long: %.*s", (int)(argp - savep),
1029 			    savep);
1030 			optfatal = 1;
1031 		}
1032 		/*
1033 		 * Skip over any number of trailing whitespace characters,
1034 		 * but only one (at most) trailing element-terminating
1035 		 * character.
1036 		 */
1037 		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
1038 			argp++;
1039 		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
1040 			argp++;
1041 			/* Catch case where string ended with a comma. */
1042 			if (*argp == '\0')
1043 				inf->addelem(inf, argp);
1044 		}
1045 	}
1046 }
1047 
1048 static void
1049 descendant_sort(KINFO *ki, int items)
1050 {
1051 	int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
1052 	unsigned char *path;
1053 	KINFO kn;
1054 
1055 	/*
1056 	 * First, sort the entries by descendancy, tracking the descendancy
1057 	 * depth in the ki_d.level field.
1058 	 */
1059 	src = 0;
1060 	maxlvl = 0;
1061 	while (src < items) {
1062 		if (ki[src].ki_d.level) {
1063 			src++;
1064 			continue;
1065 		}
1066 		for (nsrc = 1; src + nsrc < items; nsrc++)
1067 			if (!ki[src + nsrc].ki_d.level)
1068 				break;
1069 
1070 		for (dst = 0; dst < items; dst++) {
1071 			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
1072 				continue;
1073 			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
1074 				break;
1075 		}
1076 
1077 		if (dst == items) {
1078 			src += nsrc;
1079 			continue;
1080 		}
1081 
1082 		for (ndst = 1; dst + ndst < items; ndst++)
1083 			if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
1084 				break;
1085 
1086 		for (n = src; n < src + nsrc; n++) {
1087 			ki[n].ki_d.level += ki[dst].ki_d.level + 1;
1088 			if (maxlvl < ki[n].ki_d.level)
1089 				maxlvl = ki[n].ki_d.level;
1090 		}
1091 
1092 		while (nsrc) {
1093 			if (src < dst) {
1094 				kn = ki[src];
1095 				memmove(ki + src, ki + src + 1,
1096 				    (dst - src + ndst - 1) * sizeof *ki);
1097 				ki[dst + ndst - 1] = kn;
1098 				nsrc--;
1099 				dst--;
1100 				ndst++;
1101 			} else if (src != dst + ndst) {
1102 				kn = ki[src];
1103 				memmove(ki + dst + ndst + 1, ki + dst + ndst,
1104 				    (src - dst - ndst) * sizeof *ki);
1105 				ki[dst + ndst] = kn;
1106 				ndst++;
1107 				nsrc--;
1108 				src++;
1109 			} else {
1110 				ndst += nsrc;
1111 				src += nsrc;
1112 				nsrc = 0;
1113 			}
1114 		}
1115 	}
1116 
1117 	/*
1118 	 * Now populate ki_d.prefix (instead of ki_d.level) with the command
1119 	 * prefix used to show descendancies.
1120 	 */
1121 	path = calloc((maxlvl + 7) / 8, sizeof(unsigned char));
1122 	for (src = 0; src < items; src++) {
1123 		if ((lvl = ki[src].ki_d.level) == 0) {
1124 			ki[src].ki_d.prefix = NULL;
1125 			continue;
1126 		}
1127 		if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
1128 			xo_errx(1, "malloc failed");
1129 		for (n = 0; n < lvl - 2; n++) {
1130 			ki[src].ki_d.prefix[n * 2] =
1131 			    path[n / 8] & 1 << (n % 8) ? '|' : ' ';
1132 			ki[src].ki_d.prefix[n * 2 + 1] = ' ';
1133 		}
1134 		if (n == lvl - 2) {
1135 			/* Have I any more siblings? */
1136 			for (siblings = 0, dst = src + 1; dst < items; dst++) {
1137 				if (ki[dst].ki_d.level > lvl)
1138 					continue;
1139 				if (ki[dst].ki_d.level == lvl)
1140 					siblings = 1;
1141 				break;
1142 			}
1143 			if (siblings)
1144 				path[n / 8] |= 1 << (n % 8);
1145 			else
1146 				path[n / 8] &= ~(1 << (n % 8));
1147 			ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1148 			ki[src].ki_d.prefix[n * 2 + 1] = '-';
1149 			n++;
1150 		}
1151 		strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1152 	}
1153 	free(path);
1154 }
1155 
1156 static void *
1157 expand_list(struct listinfo *inf)
1158 {
1159 	void *newlist;
1160 	int newmax;
1161 
1162 	newmax = (inf->maxcount + 1) << 1;
1163 	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1164 	if (newlist == NULL) {
1165 		free(inf->l.ptr);
1166 		xo_errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1167 	}
1168 	inf->maxcount = newmax;
1169 	inf->l.ptr = newlist;
1170 
1171 	return (newlist);
1172 }
1173 
1174 static void
1175 free_list(struct listinfo *inf)
1176 {
1177 
1178 	inf->count = inf->elemsize = inf->maxcount = 0;
1179 	if (inf->l.ptr != NULL)
1180 		free(inf->l.ptr);
1181 	inf->addelem = NULL;
1182 	inf->lname = NULL;
1183 	inf->l.ptr = NULL;
1184 }
1185 
1186 static void
1187 init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1188     const char *lname)
1189 {
1190 
1191 	inf->count = inf->maxcount = 0;
1192 	inf->elemsize = elemsize;
1193 	inf->addelem = artn;
1194 	inf->lname = lname;
1195 	inf->l.ptr = NULL;
1196 }
1197 
1198 VARENT *
1199 find_varentry(VAR *v)
1200 {
1201 	struct varent *vent;
1202 
1203 	STAILQ_FOREACH(vent, &varlist, next_ve) {
1204 		if (strcmp(vent->var->name, v->name) == 0)
1205 			return vent;
1206 	}
1207 	return NULL;
1208 }
1209 
1210 static void
1211 scanvars(void)
1212 {
1213 	struct varent *vent;
1214 	VAR *v;
1215 
1216 	STAILQ_FOREACH(vent, &varlist, next_ve) {
1217 		v = vent->var;
1218 		if (v->flag & USER)
1219 			needuser = 1;
1220 		if (v->flag & COMM)
1221 			needcomm = 1;
1222 	}
1223 }
1224 
1225 static void
1226 format_output(KINFO *ki)
1227 {
1228 	struct varent *vent;
1229 	VAR *v;
1230 	KINFO_STR *ks;
1231 	char *str;
1232 	int len;
1233 
1234 	STAILQ_INIT(&ki->ki_ks);
1235 	STAILQ_FOREACH(vent, &varlist, next_ve) {
1236 		v = vent->var;
1237 		str = (v->oproc)(ki, vent);
1238 		ks = malloc(sizeof(*ks));
1239 		if (ks == NULL)
1240 			xo_errx(1, "malloc failed");
1241 		ks->ks_str = str;
1242 		STAILQ_INSERT_TAIL(&ki->ki_ks, ks, ks_next);
1243 		if (str != NULL) {
1244 			len = strlen(str);
1245 		} else
1246 			len = 1; /* "-" */
1247 		if (v->width < len)
1248 			v->width = len;
1249 	}
1250 }
1251 
1252 static void
1253 sizevars(void)
1254 {
1255 	struct varent *vent;
1256 	VAR *v;
1257 	int i;
1258 
1259 	STAILQ_FOREACH(vent, &varlist, next_ve) {
1260 		v = vent->var;
1261 		i = strlen(vent->header);
1262 		if (v->width < i)
1263 			v->width = i;
1264 	}
1265 }
1266 
1267 static const char *
1268 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
1269     char *comm, char *thread, int maxlen)
1270 {
1271 	const char *s;
1272 
1273 	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm,
1274 	    showthreads && ki->ki_p->ki_numthreads > 1 ? thread : NULL, maxlen);
1275 	return (s);
1276 }
1277 
1278 #define UREADOK(ki)	(forceuread || (ki->ki_p->ki_flag & P_INMEM))
1279 
1280 static void
1281 saveuser(KINFO *ki)
1282 {
1283 	char tdname[COMMLEN + 1];
1284 	char *argsp;
1285 
1286 	if (ki->ki_p->ki_flag & P_INMEM) {
1287 		/*
1288 		 * The u-area might be swapped out, and we can't get
1289 		 * at it because we have a crashdump and no swap.
1290 		 * If it's here fill in these fields, otherwise, just
1291 		 * leave them 0.
1292 		 */
1293 		ki->ki_valid = 1;
1294 	} else
1295 		ki->ki_valid = 0;
1296 	/*
1297 	 * save arguments if needed
1298 	 */
1299 	if (needcomm) {
1300 		if (ki->ki_p->ki_stat == SZOMB) {
1301 			ki->ki_args = strdup("<defunct>");
1302 		} else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL)) {
1303 			(void)snprintf(tdname, sizeof(tdname), "%s%s",
1304 			    ki->ki_p->ki_tdname, ki->ki_p->ki_moretdname);
1305 			ki->ki_args = fmt(kvm_getargv, ki,
1306 			    ki->ki_p->ki_comm, tdname, COMMLEN * 2 + 1);
1307 		} else {
1308 			asprintf(&argsp, "(%s)", ki->ki_p->ki_comm);
1309 			ki->ki_args = argsp;
1310 		}
1311 		if (ki->ki_args == NULL)
1312 			xo_errx(1, "malloc failed");
1313 	} else {
1314 		ki->ki_args = NULL;
1315 	}
1316 	if (needenv) {
1317 		if (UREADOK(ki))
1318 			ki->ki_env = fmt(kvm_getenvv, ki,
1319 			    (char *)NULL, (char *)NULL, 0);
1320 		else
1321 			ki->ki_env = strdup("()");
1322 		if (ki->ki_env == NULL)
1323 			xo_errx(1, "malloc failed");
1324 	} else {
1325 		ki->ki_env = NULL;
1326 	}
1327 }
1328 
1329 /* A macro used to improve the readability of pscomp(). */
1330 #define	DIFF_RETURN(a, b, field) do {	\
1331 	if ((a)->field != (b)->field)	\
1332 		return (((a)->field < (b)->field) ? -1 : 1); 	\
1333 } while (0)
1334 
1335 static int
1336 pscomp(const void *a, const void *b)
1337 {
1338 	const KINFO *ka, *kb;
1339 
1340 	ka = a;
1341 	kb = b;
1342 	/* SORTCPU and SORTMEM are sorted in descending order. */
1343 	if (sortby == SORTCPU)
1344 		DIFF_RETURN(kb, ka, ki_pcpu);
1345 	if (sortby == SORTMEM)
1346 		DIFF_RETURN(kb, ka, ki_memsize);
1347 	/*
1348 	 * TTY's are sorted in ascending order, except that all NODEV
1349 	 * processes come before all processes with a device.
1350 	 */
1351 	if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1352 		if (ka->ki_p->ki_tdev == NODEV)
1353 			return (-1);
1354 		if (kb->ki_p->ki_tdev == NODEV)
1355 			return (1);
1356 		DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1357 	}
1358 
1359 	/* PID's and TID's (threads) are sorted in ascending order. */
1360 	DIFF_RETURN(ka, kb, ki_p->ki_pid);
1361 	DIFF_RETURN(ka, kb, ki_p->ki_tid);
1362 	return (0);
1363 }
1364 #undef DIFF_RETURN
1365 
1366 /*
1367  * ICK (all for getopt), would rather hide the ugliness
1368  * here than taint the main code.
1369  *
1370  *  ps foo -> ps -foo
1371  *  ps 34 -> ps -p34
1372  *
1373  * The old convention that 't' with no trailing tty arg means the users
1374  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1375  * feature is available with the option 'T', which takes no argument.
1376  */
1377 static char *
1378 kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1379 {
1380 	size_t len;
1381 	char *argp, *cp, *newopts, *ns, *optp, *pidp;
1382 
1383 	/*
1384 	 * See if the original value includes any option which takes an
1385 	 * argument (and will thus use up the remainder of the string).
1386 	 */
1387 	argp = NULL;
1388 	if (optlist != NULL) {
1389 		for (cp = origval; *cp != '\0'; cp++) {
1390 			optp = strchr(optlist, *cp);
1391 			if ((optp != NULL) && *(optp + 1) == ':') {
1392 				argp = cp;
1393 				break;
1394 			}
1395 		}
1396 	}
1397 	if (argp != NULL && *origval == '-')
1398 		return (origval);
1399 
1400 	/*
1401 	 * if last letter is a 't' flag with no argument (in the context
1402 	 * of the oldps options -- option string NOT starting with a '-' --
1403 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1404 	 *
1405 	 * However, if a flag accepting a string argument is found earlier
1406 	 * in the option string (including a possible `t' flag), then the
1407 	 * remainder of the string must be the argument to that flag; so
1408 	 * do not modify that argument.  Note that a trailing `t' would
1409 	 * cause argp to be set, if argp was not already set by some
1410 	 * earlier option.
1411 	 */
1412 	len = strlen(origval);
1413 	cp = origval + len - 1;
1414 	pidp = NULL;
1415 	if (*cp == 't' && *origval != '-' && cp == argp) {
1416 		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1417 			*cp = 'T';
1418 	} else if (argp == NULL) {
1419 		/*
1420 		 * The original value did not include any option which takes
1421 		 * an argument (and that would include `p' and `t'), so check
1422 		 * the value for trailing number, or comma-separated list of
1423 		 * numbers, which we will treat as a pid request.
1424 		 */
1425 		if (isdigitch(*cp)) {
1426 			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1427 				--cp;
1428 			pidp = cp + 1;
1429 		}
1430 	}
1431 
1432 	/*
1433 	 * If nothing needs to be added to the string, then return
1434 	 * the "original" (although possibly modified) value.
1435 	 */
1436 	if (*origval == '-' && pidp == NULL)
1437 		return (origval);
1438 
1439 	/*
1440 	 * Create a copy of the string to add '-' and/or 'p' to the
1441 	 * original value.
1442 	 */
1443 	if ((newopts = ns = malloc(len + 3)) == NULL)
1444 		xo_errx(1, "malloc failed");
1445 
1446 	if (*origval != '-')
1447 		*ns++ = '-';	/* add option flag */
1448 
1449 	if (pidp == NULL)
1450 		strcpy(ns, origval);
1451 	else {
1452 		/*
1453 		 * Copy everything before the pid string, add the `p',
1454 		 * and then copy the pid string.
1455 		 */
1456 		len = pidp - origval;
1457 		memcpy(ns, origval, len);
1458 		ns += len;
1459 		*ns++ = 'p';
1460 		strcpy(ns, pidp);
1461 	}
1462 
1463 	return (newopts);
1464 }
1465 
1466 static void
1467 pidmax_init(void)
1468 {
1469 	size_t intsize;
1470 
1471 	intsize = sizeof(pid_max);
1472 	if (sysctlbyname("kern.pid_max", &pid_max, &intsize, NULL, 0) < 0) {
1473 		xo_warn("unable to read kern.pid_max");
1474 		pid_max = 99999;
1475 	}
1476 }
1477 
1478 static void __dead2
1479 usage(void)
1480 {
1481 #define	SINGLE_OPTS	"[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1482 
1483 	(void)xo_error("%s\n%s\n%s\n%s\n%s\n",
1484 	    "usage: ps [--libxo] " SINGLE_OPTS " [-O fmt | -o fmt]",
1485 	    "          [-G gid[,gid...]] [-J jid[,jid...]] [-M core] [-N system]",
1486 	    "          [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",
1487 	    "          [-D up | down | both]",
1488 	    "       ps [--libxo] -L");
1489 	exit(1);
1490 }
1491