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