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