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