xref: /freebsd/bin/ps/ps.c (revision a64729f5077d77e13b9497cb33ecb3c82e606ee8)
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 #ifdef LAZY_PS
72 #define	DEF_UREAD	0
73 #define	OPT_LAZY_f	"f"
74 #else
75 #define	DEF_UREAD	1	/* Always do the more-expensive read. */
76 #define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
77 #endif
78 
79 /*
80  * isdigit takes an `int', but expects values in the range of unsigned char.
81  * This wrapper ensures that values from a 'char' end up in the correct range.
82  */
83 #define	isdigitch(Anychar) isdigit((u_char)(Anychar))
84 
85 int	 cflag;			/* -c */
86 int	 eval;			/* Exit value */
87 time_t	 now;			/* Current time(3) value */
88 int	 rawcpu;		/* -C */
89 int	 sumrusage;		/* -S */
90 int	 termwidth;		/* Width of the screen (0 == infinity). */
91 int	 showthreads;		/* will threads be shown? */
92 
93 struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
94 
95 static int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
96 static kvm_t	*kd;
97 static int	 needcomm;	/* -o "command" */
98 static int	 needenv;	/* -e */
99 static int	 needuser;	/* -o "user" */
100 static int	 optfatal;	/* Fatal error parsing some list-option. */
101 static int	 pid_max;	/* kern.pid_max */
102 
103 static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
104 
105 struct listinfo;
106 typedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
107 
108 struct listinfo {
109 	int		 count;
110 	int		 maxcount;
111 	int		 elemsize;
112 	addelem_rtn	*addelem;
113 	const char	*lname;
114 	union {
115 		gid_t	*gids;
116 		int	*jids;
117 		pid_t	*pids;
118 		dev_t	*ttys;
119 		uid_t	*uids;
120 		void	*ptr;
121 	} l;
122 };
123 
124 static int	 addelem_gid(struct listinfo *, const char *);
125 static int	 addelem_jid(struct listinfo *, const char *);
126 static int	 addelem_pid(struct listinfo *, const char *);
127 static int	 addelem_tty(struct listinfo *, const char *);
128 static int	 addelem_uid(struct listinfo *, const char *);
129 static void	 add_list(struct listinfo *, const char *);
130 static void	 descendant_sort(KINFO *, int);
131 static void	 format_output(KINFO *);
132 static void	*expand_list(struct listinfo *);
133 static const char *
134 		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
135 		    KINFO *, char *, char *, int);
136 static void	 free_list(struct listinfo *);
137 static void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
138 static char	*kludge_oldps_options(const char *, char *, const char *);
139 static int	 pscomp(const void *, const void *);
140 static void	 saveuser(KINFO *);
141 static void	 scanvars(void);
142 static void	 sizevars(void);
143 static void	 pidmax_init(void);
144 static void	 usage(void);
145 
146 static char dfmt[] = "pid,tt,state,time,command";
147 static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
148 static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
149 			"tt,time,command";
150 static char   o1[] = "pid";
151 static char   o2[] = "tt,state,time,command";
152 static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
153 static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
154 			"%cpu,%mem,command";
155 static char Zfmt[] = "label";
156 
157 #define	PS_ARGS	"AaCcD:de" OPT_LAZY_f "G:gHhjJ:LlM:mN:O:o:p:rSTt:U:uvwXxZ"
158 
159 int
160 main(int argc, char *argv[])
161 {
162 	struct listinfo gidlist, jidlist, pgrplist, pidlist;
163 	struct listinfo ruidlist, sesslist, ttylist, uidlist;
164 	struct kinfo_proc *kp;
165 	KINFO *kinfo = NULL, *next_KINFO;
166 	KINFO_STR *ks;
167 	struct varent *vent;
168 	struct winsize ws = { .ws_row = 0 };
169 	const char *nlistf, *memf, *str;
170 	char *cols;
171 	int all, ch, elem, flag, _fmt, i, lineno, linelen, left;
172 	int descendancy, nentries, nkept, nselectors;
173 	int prtheader, wflag, what, xkeep, xkeep_implied;
174 	int fwidthmin, fwidthmax;
175 	char errbuf[_POSIX2_LINE_MAX];
176 	char fmtbuf[_POSIX2_LINE_MAX];
177 	enum { NONE = 0, UP = 1, DOWN = 2, BOTH = 1 | 2 } directions = NONE;
178 	struct { int traversed; int initial; } pid_count;
179 
180 	(void) setlocale(LC_ALL, "");
181 	time(&now);			/* Used by routines in print.c. */
182 
183 	/*
184 	 * Compute default output line length before processing options.
185 	 * If COLUMNS is set, use it.  Otherwise, if this is part of an
186 	 * interactive job (i.e. one associated with a terminal), use
187 	 * the terminal width.  "Interactive" is determined by whether
188 	 * any of stdout, stderr, or stdin is a terminal.  The intent
189 	 * is that "ps", "ps | more", and "ps | grep" all use the same
190 	 * default line length unless -w is specified.
191 	 *
192 	 * If not interactive, the default length was traditionally 79.
193 	 * It has been changed to unlimited.  This is mostly for the
194 	 * benefit of non-interactive scripts, which arguably should
195 	 * use -ww, but is compatible with Linux.
196 	 */
197 	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
198 		termwidth = atoi(cols);
199 	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
200 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
201 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
202 	     ws.ws_col == 0)
203 		termwidth = UNLIMITED;
204 	else
205 		termwidth = ws.ws_col - 1;
206 
207 	/*
208 	 * Hide a number of option-processing kludges in a separate routine,
209 	 * to support some historical BSD behaviors, such as `ps axu'.
210 	 */
211 	if (argc > 1)
212 		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
213 
214 	pidmax_init();
215 
216 	all = descendancy = _fmt = nselectors = optfatal = 0;
217 	prtheader = showthreads = wflag = xkeep_implied = 0;
218 	xkeep = -1;			/* Neither -x nor -X. */
219 	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
220 	init_list(&jidlist, addelem_jid, sizeof(int), "jail id");
221 	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
222 	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
223 	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
224 	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
225 	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
226 	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
227 	memf = _PATH_DEVNULL;
228 	nlistf = NULL;
229 
230 	argc = xo_parse_args(argc, argv);
231 	if (argc < 0)
232 		exit(1);
233 
234 	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
235 		switch (ch) {
236 		case 'A':
237 			/*
238 			 * Exactly the same as `-ax'.   This has been
239 			 * added for compatibility with SUSv3, but for
240 			 * now it will not be described in the man page.
241 			 */
242 			all = xkeep = 1;
243 			break;
244 		case 'a':
245 			all = 1;
246 			break;
247 		case 'C':
248 			rawcpu = 1;
249 			break;
250 		case 'c':
251 			cflag = 1;
252 			break;
253 		case 'D': {
254 				size_t len = strlen(optarg);
255 
256 				if (len <= 2 &&
257 					strncasecmp(optarg, "up", len) == 0)
258 					directions |= UP;
259 				else if (len <= 4 &&
260 					strncasecmp(optarg, "down", len) == 0)
261 					directions |= DOWN;
262 				else if (len <= 4 &&
263 					strncasecmp(optarg, "both", len) == 0)
264 					directions |= BOTH;
265 				else
266 					usage();
267 				break;
268 			}
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 (!all && 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 && directions == NONE) {
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 		}
530 	}
531 
532 	/*
533 	 * select procs
534 	 */
535 	nentries = -1;
536 	kp = kvm_getprocs(kd, what, flag, &nentries);
537 	/*
538 	 * Ignore ESRCH to preserve behaviour of "ps -p nonexistent-pid"
539 	 * not reporting an error.
540 	 */
541 	if ((kp == NULL && errno != ESRCH) || (kp != NULL && nentries < 0))
542 		xo_errx(1, "%s", kvm_geterr(kd));
543 	nkept = 0;
544 	pid_count.initial = pidlist.count;
545 	if (directions & DOWN)
546 		for (elem = 0; elem < pidlist.count; elem++)
547 			for (i = 0; i < nentries; i++) {
548 				if (kp[i].ki_ppid == kp[i].ki_pid)
549 					continue;
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 			}
556 	pid_count.traversed = pidlist.count;
557 	if (directions & UP)
558 		for (elem = 0; elem < pidlist.count; elem++) {
559 			if (elem >= pid_count.initial && elem < pid_count.traversed)
560 				continue;
561 			for (i = 0; i < nentries; i++) {
562 				if (kp[i].ki_ppid == kp[i].ki_pid)
563 					continue;
564 				if (kp[i].ki_pid == pidlist.l.pids[elem]) {
565 					if (pidlist.count >= pidlist.maxcount)
566 						expand_list(&pidlist);
567 					pidlist.l.pids[pidlist.count++] = kp[i].ki_ppid;
568 				}
569 			}
570 		}
571 	if (nentries > 0) {
572 		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
573 			xo_errx(1, "malloc failed");
574 		for (i = nentries; --i >= 0; ++kp) {
575 			/*
576 			 * If the user specified multiple selection-criteria,
577 			 * then keep any process matched by the inclusive OR
578 			 * of all the selection-criteria given.
579 			 */
580 			if (pidlist.count > 0) {
581 				for (elem = 0; elem < pidlist.count; elem++)
582 					if (kp->ki_pid == pidlist.l.pids[elem])
583 						goto keepit;
584 			}
585 			/*
586 			 * Note that we had to process pidlist before
587 			 * filtering out processes which do not have
588 			 * a controlling terminal.
589 			 */
590 			if (xkeep == 0) {
591 				if ((kp->ki_tdev == NODEV ||
592 				    (kp->ki_flag & P_CONTROLT) == 0))
593 					continue;
594 			}
595 			if (nselectors == 0)
596 				goto keepit;
597 			if (gidlist.count > 0) {
598 				for (elem = 0; elem < gidlist.count; elem++)
599 					if (kp->ki_rgid == gidlist.l.gids[elem])
600 						goto keepit;
601 			}
602 			if (jidlist.count > 0) {
603 				for (elem = 0; elem < jidlist.count; elem++)
604 					if (kp->ki_jid == jidlist.l.jids[elem])
605 						goto keepit;
606 			}
607 			if (pgrplist.count > 0) {
608 				for (elem = 0; elem < pgrplist.count; elem++)
609 					if (kp->ki_pgid ==
610 					    pgrplist.l.pids[elem])
611 						goto keepit;
612 			}
613 			if (ruidlist.count > 0) {
614 				for (elem = 0; elem < ruidlist.count; elem++)
615 					if (kp->ki_ruid ==
616 					    ruidlist.l.uids[elem])
617 						goto keepit;
618 			}
619 			if (sesslist.count > 0) {
620 				for (elem = 0; elem < sesslist.count; elem++)
621 					if (kp->ki_sid == sesslist.l.pids[elem])
622 						goto keepit;
623 			}
624 			if (ttylist.count > 0) {
625 				for (elem = 0; elem < ttylist.count; elem++)
626 					if (kp->ki_tdev == ttylist.l.ttys[elem])
627 						goto keepit;
628 			}
629 			if (uidlist.count > 0) {
630 				for (elem = 0; elem < uidlist.count; elem++)
631 					if (kp->ki_uid == uidlist.l.uids[elem])
632 						goto keepit;
633 			}
634 			/*
635 			 * This process did not match any of the user's
636 			 * selector-options, so skip the process.
637 			 */
638 			continue;
639 
640 		keepit:
641 			next_KINFO = &kinfo[nkept];
642 			next_KINFO->ki_p = kp;
643 			next_KINFO->ki_d.level = 0;
644 			next_KINFO->ki_d.prefix = NULL;
645 			next_KINFO->ki_pcpu = getpcpu(next_KINFO);
646 			if (sortby == SORTMEM)
647 				next_KINFO->ki_memsize = kp->ki_tsize +
648 				    kp->ki_dsize + kp->ki_ssize;
649 			if (needuser)
650 				saveuser(next_KINFO);
651 			nkept++;
652 		}
653 	}
654 
655 	sizevars();
656 
657 	if (nkept == 0) {
658 		printheader();
659 		if (xo_finish() < 0)
660 			xo_err(1, "stdout");
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 	if (xo_finish() < 0)
746 		xo_err(1, "stdout");
747 
748 	free_list(&gidlist);
749 	free_list(&jidlist);
750 	free_list(&pidlist);
751 	free_list(&pgrplist);
752 	free_list(&ruidlist);
753 	free_list(&sesslist);
754 	free_list(&ttylist);
755 	free_list(&uidlist);
756 	for (i = 0; i < nkept; i++)
757 		free(kinfo[i].ki_d.prefix);
758 	free(kinfo);
759 
760 	exit(eval);
761 }
762 
763 static int
764 addelem_gid(struct listinfo *inf, const char *elem)
765 {
766 	struct group *grp;
767 	const char *nameorID;
768 	char *endp;
769 	u_long bigtemp;
770 
771 	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
772 		if (*elem == '\0')
773 			xo_warnx("Invalid (zero-length) %s name", inf->lname);
774 		else
775 			xo_warnx("%s name too long: %s", inf->lname, elem);
776 		optfatal = 1;
777 		return (0);		/* Do not add this value. */
778 	}
779 
780 	/*
781 	 * SUSv3 states that `ps -G grouplist' should match "real-group
782 	 * ID numbers", and does not mention group-names.  I do want to
783 	 * also support group-names, so this tries for a group-id first,
784 	 * and only tries for a name if that doesn't work.  This is the
785 	 * opposite order of what is done in addelem_uid(), but in
786 	 * practice the order would only matter for group-names which
787 	 * are all-numeric.
788 	 */
789 	grp = NULL;
790 	nameorID = "named";
791 	errno = 0;
792 	bigtemp = strtoul(elem, &endp, 10);
793 	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
794 		nameorID = "name or ID matches";
795 		grp = getgrgid((gid_t)bigtemp);
796 	}
797 	if (grp == NULL)
798 		grp = getgrnam(elem);
799 	if (grp == NULL) {
800 		xo_warnx("No %s %s '%s'", inf->lname, nameorID, elem);
801 		optfatal = 1;
802 		return (0);
803 	}
804 	if (inf->count >= inf->maxcount)
805 		expand_list(inf);
806 	inf->l.gids[(inf->count)++] = grp->gr_gid;
807 	return (1);
808 }
809 
810 static int
811 addelem_jid(struct listinfo *inf, const char *elem)
812 {
813 	int tempid;
814 
815 	if (*elem == '\0') {
816 		xo_warnx("Invalid (zero-length) jail id");
817 		optfatal = 1;
818 		return (0);		/* Do not add this value. */
819 	}
820 
821 	tempid = jail_getid(elem);
822 	if (tempid < 0) {
823 		xo_warnx("Invalid %s: %s", inf->lname, elem);
824 		optfatal = 1;
825 		return (0);
826 	}
827 
828 	if (inf->count >= inf->maxcount)
829 		expand_list(inf);
830 	inf->l.jids[(inf->count)++] = tempid;
831 	return (1);
832 }
833 
834 static int
835 addelem_pid(struct listinfo *inf, const char *elem)
836 {
837 	char *endp;
838 	long tempid;
839 
840 	if (*elem == '\0') {
841 		xo_warnx("Invalid (zero-length) process id");
842 		optfatal = 1;
843 		return (0);		/* Do not add this value. */
844 	}
845 
846 	errno = 0;
847 	tempid = strtol(elem, &endp, 10);
848 	if (*endp != '\0' || tempid < 0 || elem == endp) {
849 		xo_warnx("Invalid %s: %s", inf->lname, elem);
850 		errno = ERANGE;
851 	} else if (errno != 0 || tempid > pid_max) {
852 		xo_warnx("%s too large: %s", inf->lname, elem);
853 		errno = ERANGE;
854 	}
855 	if (errno == ERANGE) {
856 		optfatal = 1;
857 		return (0);
858 	}
859 	if (inf->count >= inf->maxcount)
860 		expand_list(inf);
861 	inf->l.pids[(inf->count)++] = tempid;
862 	return (1);
863 }
864 
865 /*-
866  * The user can specify a device via one of three formats:
867  *     1) fully qualified, e.g.:     /dev/ttyp0 /dev/console	/dev/pts/0
868  *     2) missing "/dev", e.g.:      ttyp0      console		pts/0
869  *     3) two-letters, e.g.:         p0         co		0
870  *        (matching letters that would be seen in the "TT" column)
871  */
872 static int
873 addelem_tty(struct listinfo *inf, const char *elem)
874 {
875 	const char *ttypath;
876 	struct stat sb;
877 	char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
878 
879 	ttypath = NULL;
880 	pathbuf2[0] = '\0';
881 	pathbuf3[0] = '\0';
882 	switch (*elem) {
883 	case '/':
884 		ttypath = elem;
885 		break;
886 	case 'c':
887 		if (strcmp(elem, "co") == 0) {
888 			ttypath = _PATH_CONSOLE;
889 			break;
890 		}
891 		/* FALLTHROUGH */
892 	default:
893 		strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
894 		strlcat(pathbuf, elem, sizeof(pathbuf));
895 		ttypath = pathbuf;
896 		if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
897 			break;
898 		if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
899 			break;
900 		if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
901 			break;
902 		/* Check to see if /dev/tty${elem} exists */
903 		strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
904 		strlcat(pathbuf2, elem, sizeof(pathbuf2));
905 		if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
906 			/* No need to repeat stat() && S_ISCHR() checks */
907 			ttypath = NULL;
908 			break;
909 		}
910 		/* Check to see if /dev/pts/${elem} exists */
911 		strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
912 		strlcat(pathbuf3, elem, sizeof(pathbuf3));
913 		if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
914 			/* No need to repeat stat() && S_ISCHR() checks */
915 			ttypath = NULL;
916 			break;
917 		}
918 		break;
919 	}
920 	if (ttypath) {
921 		if (stat(ttypath, &sb) == -1) {
922 			if (pathbuf3[0] != '\0')
923 				xo_warn("%s, %s, and %s", pathbuf3, pathbuf2,
924 				    ttypath);
925 			else
926 				xo_warn("%s", ttypath);
927 			optfatal = 1;
928 			return (0);
929 		}
930 		if (!S_ISCHR(sb.st_mode)) {
931 			if (pathbuf3[0] != '\0')
932 				xo_warnx("%s, %s, and %s: Not a terminal",
933 				    pathbuf3, pathbuf2, ttypath);
934 			else
935 				xo_warnx("%s: Not a terminal", ttypath);
936 			optfatal = 1;
937 			return (0);
938 		}
939 	}
940 	if (inf->count >= inf->maxcount)
941 		expand_list(inf);
942 	inf->l.ttys[(inf->count)++] = sb.st_rdev;
943 	return (1);
944 }
945 
946 static int
947 addelem_uid(struct listinfo *inf, const char *elem)
948 {
949 	struct passwd *pwd;
950 	char *endp;
951 	u_long bigtemp;
952 
953 	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
954 		if (*elem == '\0')
955 			xo_warnx("Invalid (zero-length) %s name", inf->lname);
956 		else
957 			xo_warnx("%s name too long: %s", inf->lname, elem);
958 		optfatal = 1;
959 		return (0);		/* Do not add this value. */
960 	}
961 
962 	pwd = getpwnam(elem);
963 	if (pwd == NULL) {
964 		errno = 0;
965 		bigtemp = strtoul(elem, &endp, 10);
966 		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
967 			xo_warnx("No %s named '%s'", inf->lname, elem);
968 		else {
969 			/* The string is all digits, so it might be a userID. */
970 			pwd = getpwuid((uid_t)bigtemp);
971 			if (pwd == NULL)
972 				xo_warnx("No %s name or ID matches '%s'",
973 				    inf->lname, elem);
974 		}
975 	}
976 	if (pwd == NULL) {
977 		/*
978 		 * These used to be treated as minor warnings (and the
979 		 * option was simply ignored), but now they are fatal
980 		 * errors (and the command will be aborted).
981 		 */
982 		optfatal = 1;
983 		return (0);
984 	}
985 	if (inf->count >= inf->maxcount)
986 		expand_list(inf);
987 	inf->l.uids[(inf->count)++] = pwd->pw_uid;
988 	return (1);
989 }
990 
991 static void
992 add_list(struct listinfo *inf, const char *argp)
993 {
994 	const char *savep;
995 	char *cp, *endp;
996 	int toolong;
997 	char elemcopy[PATH_MAX];
998 
999 	if (*argp == '\0')
1000 		inf->addelem(inf, argp);
1001 	while (*argp != '\0') {
1002 		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
1003 			argp++;
1004 		savep = argp;
1005 		toolong = 0;
1006 		cp = elemcopy;
1007 		if (strchr(T_SEP, *argp) == NULL) {
1008 			endp = elemcopy + sizeof(elemcopy) - 1;
1009 			while (*argp != '\0' && cp <= endp &&
1010 			    strchr(W_SEP T_SEP, *argp) == NULL)
1011 				*cp++ = *argp++;
1012 			if (cp > endp)
1013 				toolong = 1;
1014 		}
1015 		if (!toolong) {
1016 			*cp = '\0';
1017 			/*
1018 			 * Add this single element to the given list.
1019 			 */
1020 			inf->addelem(inf, elemcopy);
1021 		} else {
1022 			/*
1023 			 * The string is too long to copy.  Find the end
1024 			 * of the string to print out the warning message.
1025 			 */
1026 			while (*argp != '\0' && strchr(W_SEP T_SEP,
1027 			    *argp) == NULL)
1028 				argp++;
1029 			xo_warnx("Value too long: %.*s", (int)(argp - savep),
1030 			    savep);
1031 			optfatal = 1;
1032 		}
1033 		/*
1034 		 * Skip over any number of trailing whitespace characters,
1035 		 * but only one (at most) trailing element-terminating
1036 		 * character.
1037 		 */
1038 		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
1039 			argp++;
1040 		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
1041 			argp++;
1042 			/* Catch case where string ended with a comma. */
1043 			if (*argp == '\0')
1044 				inf->addelem(inf, argp);
1045 		}
1046 	}
1047 }
1048 
1049 static void
1050 descendant_sort(KINFO *ki, int items)
1051 {
1052 	int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
1053 	unsigned char *path;
1054 	KINFO kn;
1055 
1056 	/*
1057 	 * First, sort the entries by descendancy, tracking the descendancy
1058 	 * depth in the ki_d.level field.
1059 	 */
1060 	src = 0;
1061 	maxlvl = 0;
1062 	while (src < items) {
1063 		if (ki[src].ki_d.level) {
1064 			src++;
1065 			continue;
1066 		}
1067 		for (nsrc = 1; src + nsrc < items; nsrc++)
1068 			if (!ki[src + nsrc].ki_d.level)
1069 				break;
1070 
1071 		for (dst = 0; dst < items; dst++) {
1072 			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
1073 				continue;
1074 			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
1075 				break;
1076 		}
1077 
1078 		if (dst == items) {
1079 			src += nsrc;
1080 			continue;
1081 		}
1082 
1083 		for (ndst = 1; dst + ndst < items; ndst++)
1084 			if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
1085 				break;
1086 
1087 		for (n = src; n < src + nsrc; n++) {
1088 			ki[n].ki_d.level += ki[dst].ki_d.level + 1;
1089 			if (maxlvl < ki[n].ki_d.level)
1090 				maxlvl = ki[n].ki_d.level;
1091 		}
1092 
1093 		while (nsrc) {
1094 			if (src < dst) {
1095 				kn = ki[src];
1096 				memmove(ki + src, ki + src + 1,
1097 				    (dst - src + ndst - 1) * sizeof *ki);
1098 				ki[dst + ndst - 1] = kn;
1099 				nsrc--;
1100 				dst--;
1101 				ndst++;
1102 			} else if (src != dst + ndst) {
1103 				kn = ki[src];
1104 				memmove(ki + dst + ndst + 1, ki + dst + ndst,
1105 				    (src - dst - ndst) * sizeof *ki);
1106 				ki[dst + ndst] = kn;
1107 				ndst++;
1108 				nsrc--;
1109 				src++;
1110 			} else {
1111 				ndst += nsrc;
1112 				src += nsrc;
1113 				nsrc = 0;
1114 			}
1115 		}
1116 	}
1117 
1118 	/*
1119 	 * Now populate ki_d.prefix (instead of ki_d.level) with the command
1120 	 * prefix used to show descendancies.
1121 	 */
1122 	path = calloc((maxlvl + 7) / 8, sizeof(unsigned char));
1123 	for (src = 0; src < items; src++) {
1124 		if ((lvl = ki[src].ki_d.level) == 0) {
1125 			ki[src].ki_d.prefix = NULL;
1126 			continue;
1127 		}
1128 		if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
1129 			xo_errx(1, "malloc failed");
1130 		for (n = 0; n < lvl - 2; n++) {
1131 			ki[src].ki_d.prefix[n * 2] =
1132 			    path[n / 8] & 1 << (n % 8) ? '|' : ' ';
1133 			ki[src].ki_d.prefix[n * 2 + 1] = ' ';
1134 		}
1135 		if (n == lvl - 2) {
1136 			/* Have I any more siblings? */
1137 			for (siblings = 0, dst = src + 1; dst < items; dst++) {
1138 				if (ki[dst].ki_d.level > lvl)
1139 					continue;
1140 				if (ki[dst].ki_d.level == lvl)
1141 					siblings = 1;
1142 				break;
1143 			}
1144 			if (siblings)
1145 				path[n / 8] |= 1 << (n % 8);
1146 			else
1147 				path[n / 8] &= ~(1 << (n % 8));
1148 			ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1149 			ki[src].ki_d.prefix[n * 2 + 1] = '-';
1150 			n++;
1151 		}
1152 		strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1153 	}
1154 	free(path);
1155 }
1156 
1157 static void *
1158 expand_list(struct listinfo *inf)
1159 {
1160 	void *newlist;
1161 	int newmax;
1162 
1163 	newmax = (inf->maxcount + 1) << 1;
1164 	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1165 	if (newlist == NULL) {
1166 		free(inf->l.ptr);
1167 		xo_errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1168 	}
1169 	inf->maxcount = newmax;
1170 	inf->l.ptr = newlist;
1171 
1172 	return (newlist);
1173 }
1174 
1175 static void
1176 free_list(struct listinfo *inf)
1177 {
1178 
1179 	inf->count = inf->elemsize = inf->maxcount = 0;
1180 	if (inf->l.ptr != NULL)
1181 		free(inf->l.ptr);
1182 	inf->addelem = NULL;
1183 	inf->lname = NULL;
1184 	inf->l.ptr = NULL;
1185 }
1186 
1187 static void
1188 init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1189     const char *lname)
1190 {
1191 
1192 	inf->count = inf->maxcount = 0;
1193 	inf->elemsize = elemsize;
1194 	inf->addelem = artn;
1195 	inf->lname = lname;
1196 	inf->l.ptr = NULL;
1197 }
1198 
1199 VARENT *
1200 find_varentry(VAR *v)
1201 {
1202 	struct varent *vent;
1203 
1204 	STAILQ_FOREACH(vent, &varlist, next_ve) {
1205 		if (strcmp(vent->var->name, v->name) == 0)
1206 			return vent;
1207 	}
1208 	return NULL;
1209 }
1210 
1211 static void
1212 scanvars(void)
1213 {
1214 	struct varent *vent;
1215 	VAR *v;
1216 
1217 	STAILQ_FOREACH(vent, &varlist, next_ve) {
1218 		v = vent->var;
1219 		if (v->flag & USER)
1220 			needuser = 1;
1221 		if (v->flag & COMM)
1222 			needcomm = 1;
1223 	}
1224 }
1225 
1226 static void
1227 format_output(KINFO *ki)
1228 {
1229 	struct varent *vent;
1230 	VAR *v;
1231 	KINFO_STR *ks;
1232 	char *str;
1233 	int len;
1234 
1235 	STAILQ_INIT(&ki->ki_ks);
1236 	STAILQ_FOREACH(vent, &varlist, next_ve) {
1237 		v = vent->var;
1238 		str = (v->oproc)(ki, vent);
1239 		ks = malloc(sizeof(*ks));
1240 		if (ks == NULL)
1241 			xo_errx(1, "malloc failed");
1242 		ks->ks_str = str;
1243 		STAILQ_INSERT_TAIL(&ki->ki_ks, ks, ks_next);
1244 		if (str != NULL) {
1245 			len = strlen(str);
1246 		} else
1247 			len = 1; /* "-" */
1248 		if (v->width < len)
1249 			v->width = len;
1250 	}
1251 }
1252 
1253 static void
1254 sizevars(void)
1255 {
1256 	struct varent *vent;
1257 	VAR *v;
1258 	int i;
1259 
1260 	STAILQ_FOREACH(vent, &varlist, next_ve) {
1261 		v = vent->var;
1262 		i = strlen(vent->header);
1263 		if (v->width < i)
1264 			v->width = i;
1265 	}
1266 }
1267 
1268 static const char *
1269 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
1270     char *comm, char *thread, int maxlen)
1271 {
1272 	const char *s;
1273 
1274 	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm,
1275 	    showthreads && ki->ki_p->ki_numthreads > 1 ? thread : NULL, maxlen);
1276 	return (s);
1277 }
1278 
1279 #define UREADOK(ki)	(forceuread || (ki->ki_p->ki_flag & P_INMEM))
1280 
1281 static void
1282 saveuser(KINFO *ki)
1283 {
1284 	char tdname[COMMLEN + 1];
1285 	char *argsp;
1286 
1287 	if (ki->ki_p->ki_flag & P_INMEM) {
1288 		/*
1289 		 * The u-area might be swapped out, and we can't get
1290 		 * at it because we have a crashdump and no swap.
1291 		 * If it's here fill in these fields, otherwise, just
1292 		 * leave them 0.
1293 		 */
1294 		ki->ki_valid = 1;
1295 	} else
1296 		ki->ki_valid = 0;
1297 	/*
1298 	 * save arguments if needed
1299 	 */
1300 	if (needcomm) {
1301 		if (ki->ki_p->ki_stat == SZOMB) {
1302 			ki->ki_args = strdup("<defunct>");
1303 		} else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL)) {
1304 			(void)snprintf(tdname, sizeof(tdname), "%s%s",
1305 			    ki->ki_p->ki_tdname, ki->ki_p->ki_moretdname);
1306 			ki->ki_args = fmt(kvm_getargv, ki,
1307 			    ki->ki_p->ki_comm, tdname, COMMLEN * 2 + 1);
1308 		} else {
1309 			asprintf(&argsp, "(%s)", ki->ki_p->ki_comm);
1310 			ki->ki_args = argsp;
1311 		}
1312 		if (ki->ki_args == NULL)
1313 			xo_errx(1, "malloc failed");
1314 	} else {
1315 		ki->ki_args = NULL;
1316 	}
1317 	if (needenv) {
1318 		if (UREADOK(ki))
1319 			ki->ki_env = fmt(kvm_getenvv, ki,
1320 			    (char *)NULL, (char *)NULL, 0);
1321 		else
1322 			ki->ki_env = strdup("()");
1323 		if (ki->ki_env == NULL)
1324 			xo_errx(1, "malloc failed");
1325 	} else {
1326 		ki->ki_env = NULL;
1327 	}
1328 }
1329 
1330 /* A macro used to improve the readability of pscomp(). */
1331 #define	DIFF_RETURN(a, b, field) do {	\
1332 	if ((a)->field != (b)->field)	\
1333 		return (((a)->field < (b)->field) ? -1 : 1); 	\
1334 } while (0)
1335 
1336 static int
1337 pscomp(const void *a, const void *b)
1338 {
1339 	const KINFO *ka, *kb;
1340 
1341 	ka = a;
1342 	kb = b;
1343 	/* SORTCPU and SORTMEM are sorted in descending order. */
1344 	if (sortby == SORTCPU)
1345 		DIFF_RETURN(kb, ka, ki_pcpu);
1346 	if (sortby == SORTMEM)
1347 		DIFF_RETURN(kb, ka, ki_memsize);
1348 	/*
1349 	 * TTY's are sorted in ascending order, except that all NODEV
1350 	 * processes come before all processes with a device.
1351 	 */
1352 	if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1353 		if (ka->ki_p->ki_tdev == NODEV)
1354 			return (-1);
1355 		if (kb->ki_p->ki_tdev == NODEV)
1356 			return (1);
1357 		DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1358 	}
1359 
1360 	/* PID's and TID's (threads) are sorted in ascending order. */
1361 	DIFF_RETURN(ka, kb, ki_p->ki_pid);
1362 	DIFF_RETURN(ka, kb, ki_p->ki_tid);
1363 	return (0);
1364 }
1365 #undef DIFF_RETURN
1366 
1367 /*
1368  * ICK (all for getopt), would rather hide the ugliness
1369  * here than taint the main code.
1370  *
1371  *  ps foo -> ps -foo
1372  *  ps 34 -> ps -p34
1373  *
1374  * The old convention that 't' with no trailing tty arg means the users
1375  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1376  * feature is available with the option 'T', which takes no argument.
1377  */
1378 static char *
1379 kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1380 {
1381 	size_t len;
1382 	char *argp, *cp, *newopts, *ns, *optp, *pidp;
1383 
1384 	/*
1385 	 * See if the original value includes any option which takes an
1386 	 * argument (and will thus use up the remainder of the string).
1387 	 */
1388 	argp = NULL;
1389 	if (optlist != NULL) {
1390 		for (cp = origval; *cp != '\0'; cp++) {
1391 			optp = strchr(optlist, *cp);
1392 			if ((optp != NULL) && *(optp + 1) == ':') {
1393 				argp = cp;
1394 				break;
1395 			}
1396 		}
1397 	}
1398 	if (argp != NULL && *origval == '-')
1399 		return (origval);
1400 
1401 	/*
1402 	 * if last letter is a 't' flag with no argument (in the context
1403 	 * of the oldps options -- option string NOT starting with a '-' --
1404 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1405 	 *
1406 	 * However, if a flag accepting a string argument is found earlier
1407 	 * in the option string (including a possible `t' flag), then the
1408 	 * remainder of the string must be the argument to that flag; so
1409 	 * do not modify that argument.  Note that a trailing `t' would
1410 	 * cause argp to be set, if argp was not already set by some
1411 	 * earlier option.
1412 	 */
1413 	len = strlen(origval);
1414 	cp = origval + len - 1;
1415 	pidp = NULL;
1416 	if (*cp == 't' && *origval != '-' && cp == argp) {
1417 		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1418 			*cp = 'T';
1419 	} else if (argp == NULL) {
1420 		/*
1421 		 * The original value did not include any option which takes
1422 		 * an argument (and that would include `p' and `t'), so check
1423 		 * the value for trailing number, or comma-separated list of
1424 		 * numbers, which we will treat as a pid request.
1425 		 */
1426 		if (isdigitch(*cp)) {
1427 			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1428 				--cp;
1429 			pidp = cp + 1;
1430 		}
1431 	}
1432 
1433 	/*
1434 	 * If nothing needs to be added to the string, then return
1435 	 * the "original" (although possibly modified) value.
1436 	 */
1437 	if (*origval == '-' && pidp == NULL)
1438 		return (origval);
1439 
1440 	/*
1441 	 * Create a copy of the string to add '-' and/or 'p' to the
1442 	 * original value.
1443 	 */
1444 	if ((newopts = ns = malloc(len + 3)) == NULL)
1445 		xo_errx(1, "malloc failed");
1446 
1447 	if (*origval != '-')
1448 		*ns++ = '-';	/* add option flag */
1449 
1450 	if (pidp == NULL)
1451 		strcpy(ns, origval);
1452 	else {
1453 		/*
1454 		 * Copy everything before the pid string, add the `p',
1455 		 * and then copy the pid string.
1456 		 */
1457 		len = pidp - origval;
1458 		memcpy(ns, origval, len);
1459 		ns += len;
1460 		*ns++ = 'p';
1461 		strcpy(ns, pidp);
1462 	}
1463 
1464 	return (newopts);
1465 }
1466 
1467 static void
1468 pidmax_init(void)
1469 {
1470 	size_t intsize;
1471 
1472 	intsize = sizeof(pid_max);
1473 	if (sysctlbyname("kern.pid_max", &pid_max, &intsize, NULL, 0) < 0) {
1474 		xo_warn("unable to read kern.pid_max");
1475 		pid_max = 99999;
1476 	}
1477 }
1478 
1479 static void __dead2
1480 usage(void)
1481 {
1482 #define	SINGLE_OPTS	"[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1483 
1484 	xo_error("%s\n%s\n%s\n%s\n%s\n",
1485 	    "usage: ps [--libxo] " SINGLE_OPTS " [-O fmt | -o fmt]",
1486 	    "          [-G gid[,gid...]] [-J jid[,jid...]] [-M core] [-N system]",
1487 	    "          [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",
1488 	    "          [-D up | down | both]",
1489 	    "       ps [--libxo] -L");
1490 	exit(1);
1491 }
1492