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