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