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