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