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