ps.c revision 127539
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 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 * ------+---------+---------+-------- + --------+---------+---------+---------*
33 * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
34 * All rights reserved.
35 *
36 * Significant modifications made to bring `ps' options somewhat closer
37 * to the standard for `ps' as described in SingleUnixSpec-v3.
38 * ------+---------+---------+-------- + --------+---------+---------+---------*
39 */
40
41#ifndef lint
42static const char copyright[] =
43"@(#) Copyright (c) 1990, 1993, 1994\n\
44	The Regents of the University of California.  All rights reserved.\n";
45#endif /* not lint */
46
47#if 0
48#ifndef lint
49static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
50#endif /* not lint */
51#endif
52
53#include <sys/cdefs.h>
54__FBSDID("$FreeBSD: head/bin/ps/ps.c 127539 2004-03-29 00:25:09Z gad $");
55
56#include <sys/param.h>
57#include <sys/user.h>
58#include <sys/stat.h>
59#include <sys/ioctl.h>
60#include <sys/sysctl.h>
61
62#include <ctype.h>
63#include <err.h>
64#include <errno.h>
65#include <fcntl.h>
66#include <grp.h>
67#include <kvm.h>
68#include <limits.h>
69#include <locale.h>
70#include <paths.h>
71#include <pwd.h>
72#include <stdint.h>
73#include <stdio.h>
74#include <stdlib.h>
75#include <string.h>
76#include <unistd.h>
77
78#include "ps.h"
79
80#define	W_SEP	" \t"		/* "Whitespace" list separators */
81#define	T_SEP	","		/* "Terminate-element" list separators */
82
83#ifdef LAZY_PS
84#define	DEF_UREAD	0;
85#define	OPT_LAZY_f	"f"
86#else
87#define	DEF_UREAD	1;	/* Always do the more-expensive read. */
88#define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
89#endif
90
91int	 cflag;			/* -c */
92int	 eval;			/* Exit value */
93time_t	 now;			/* Current time(3) value */
94int	 rawcpu;		/* -C */
95int	 sumrusage;		/* -S */
96int	 termwidth;		/* Width of the screen (0 == infinity). */
97int	 totwidth;		/* Calculated-width of requested variables. */
98
99struct varent *vhead;
100
101static int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
102static kvm_t	*kd;
103static KINFO	*kinfo;
104static int	 needcomm;	/* -o "command" */
105static int	 needenv;	/* -e */
106static int	 needuser;	/* -o "user" */
107static int	 optfatal;	/* Fatal error parsing some list-option. */
108
109static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
110
111struct listinfo;
112typedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
113
114struct listinfo {
115	int		 count;
116	int		 maxcount;
117	int		 elemsize;
118	addelem_rtn	*addelem;
119	const char	*lname;
120	union {
121		gid_t	*gids;
122		pid_t	*pids;
123		dev_t	*ttys;
124		uid_t	*uids;
125		void	*ptr;
126	};
127};
128
129static int	 addelem_gid(struct listinfo *, const char *);
130static int	 addelem_pid(struct listinfo *, const char *);
131static int	 addelem_tty(struct listinfo *, const char *);
132static int	 addelem_uid(struct listinfo *, const char *);
133static void	 add_list(struct listinfo *, const char *);
134static void	 dynsizevars(KINFO *);
135static void	*expand_list(struct listinfo *);
136static const char *fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
137		    KINFO *, char *, int);
138static void	 free_list(struct listinfo *);
139static void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
140static char	*kludge_oldps_options(char *);
141static int	 pscomp(const void *, const void *);
142static void	 saveuser(KINFO *);
143static void	 scanvars(void);
144static void	 sizevars(void);
145static void	 usage(void);
146
147static char dfmt[] = "pid,tt,state,time,command";
148static char jfmt[] = "user,pid,ppid,pgid,jobc,state,tt,time,command";
149static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
150			"tt,time,command";
151static char   o1[] = "pid";
152static char   o2[] = "tt,state,time,command";
153static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
154static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
155			"%cpu,%mem,command";
156static char Zfmt[] = "label";
157
158#define	PS_ARGS	"AaCc" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
159
160int
161main(int argc, char *argv[])
162{
163	struct listinfo gidlist, pgrplist, pidlist;
164	struct listinfo ruidlist, sesslist, ttylist, uidlist;
165	struct kinfo_proc *kp;
166	struct varent *vent;
167	struct winsize ws;
168	const char *cp, *nlistf, *memf;
169	char *cols;
170	int all, ch, dropgid, elem, flag, _fmt, i, lineno;
171	int nentries, nocludge, nkept, nselectors;
172	int prtheader, showthreads, wflag, what, xkeep, xkeep_implied;
173	char errbuf[_POSIX2_LINE_MAX];
174
175	(void) setlocale(LC_ALL, "");
176	/* Set the time to what it is right now. */
177	time(&now);
178
179	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
180		termwidth = atoi(cols);
181	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
182	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
183	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
184	     ws.ws_col == 0)
185		termwidth = 79;
186	else
187		termwidth = ws.ws_col - 1;
188
189	/*
190	 * Don't apply a kludge if the first argument is an option taking an
191	 * argument
192	 */
193	if (argc > 1) {
194		nocludge = 0;
195		if (argv[1][0] == '-') {
196			for (cp = PS_ARGS; *cp != '\0'; cp++) {
197				if (*cp != ':')
198					continue;
199				if (*(cp - 1) == argv[1][1]) {
200					nocludge = 1;
201					break;
202				}
203			}
204		}
205		if (nocludge == 0)
206			argv[1] = kludge_oldps_options(argv[1]);
207	}
208
209	xkeep = -1;				/* Neither -x nor -X */
210	all = _fmt = nselectors = prtheader = wflag = xkeep_implied = 0;
211	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
212	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
213	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
214	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
215	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
216	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
217	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
218	dropgid = 0;
219	optfatal = 0;
220	memf = nlistf = _PATH_DEVNULL;
221	showthreads = 0;
222	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
223		switch((char)ch) {
224		case 'A':
225			/*
226			 * Exactly the same as `-ax'.   This has been
227			 * added for compatability with SUSv3, but for
228			 * now it will not be described in the man page.
229			 */
230			nselectors++;
231			all = xkeep = 1;
232			break;
233		case 'a':
234			nselectors++;
235			all = 1;
236			break;
237		case 'C':
238			rawcpu = 1;
239			break;
240		case 'c':
241			cflag = 1;
242			break;
243		case 'e':			/* XXX set ufmt */
244			needenv = 1;
245			break;
246#ifdef LAZY_PS
247		case 'f':
248			if (getuid() == 0 || getgid() == 0)
249			    forceuread = 1;
250			break;
251#endif
252		case 'G':
253			add_list(&gidlist, optarg);
254			xkeep_implied = 1;
255			nselectors++;
256			break;
257#if 0
258		/* XXX - This SUSv3 option is still under debate. */
259		/* (it conflicts with the undocumented `-g' option) */
260		case 'g':
261			add_list(&pgrplist, optarg);
262			xkeep_implied = 1;
263			nselectors++;
264			break;
265#else
266		case 'g':
267			/* Historical BSD-ish (from SunOS) option */
268			break;			/* no-op */
269#endif
270		case 'H':
271			showthreads = KERN_PROC_INC_THREAD;
272			break;
273		case 'h':
274			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
275			break;
276		case 'j':
277			parsefmt(jfmt, 0);
278			_fmt = 1;
279			jfmt[0] = '\0';
280			break;
281		case 'L':
282			showkey();
283			exit(0);
284		case 'l':
285			parsefmt(lfmt, 0);
286			_fmt = 1;
287			lfmt[0] = '\0';
288			break;
289		case 'M':
290			memf = optarg;
291			dropgid = 1;
292			break;
293		case 'm':
294			sortby = SORTMEM;
295			break;
296		case 'N':
297			nlistf = optarg;
298			dropgid = 1;
299			break;
300		case 'O':
301			parsefmt(o1, 1);
302			parsefmt(optarg, 1);
303			parsefmt(o2, 1);
304			o1[0] = o2[0] = '\0';
305			_fmt = 1;
306			break;
307		case 'o':
308			parsefmt(optarg, 1);
309			_fmt = 1;
310			break;
311		case 'p':
312			add_list(&pidlist, optarg);
313			/*
314			 * Note: `-p' does not *set* xkeep, but any values
315			 * from pidlist are checked before xkeep is.  That
316			 * way they are always matched, even if the user
317			 * specifies `-X'.
318			 */
319			nselectors++;
320			break;
321#if 0
322		/* XXX - This un-standard option is still under debate. */
323		case 'R':
324			/* This is what SUSv3 defines as the `-U' option. */
325			add_list(&ruidlist, optarg);
326			xkeep_implied = 1;
327			nselectors++;
328			break;
329#endif
330		case 'r':
331			sortby = SORTCPU;
332			break;
333		case 'S':
334			sumrusage = 1;
335			break;
336#if 0
337		/* XXX - This non-standard option is still under debate. */
338		/* (it conflicts with `-s' in NetBSD) */
339		case 's':
340			/* As seen on Solaris, Linux, IRIX. */
341			add_list(&sesslist, optarg);
342			xkeep_implied = 1;
343			nselectors++;
344			break;
345#endif
346		case 'T':
347			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
348				errx(1, "stdin: not a terminal");
349			/* FALLTHROUGH */
350		case 't':
351			add_list(&ttylist, optarg);
352			xkeep_implied = 1;
353			nselectors++;
354			break;
355		case 'U':
356			/* This is what SUSv3 defines as the `-u' option. */
357			add_list(&uidlist, optarg);
358			xkeep_implied = 1;
359			nselectors++;
360			break;
361		case 'u':
362			parsefmt(ufmt, 0);
363			sortby = SORTCPU;
364			_fmt = 1;
365			ufmt[0] = '\0';
366			break;
367		case 'v':
368			parsefmt(vfmt, 0);
369			sortby = SORTMEM;
370			_fmt = 1;
371			vfmt[0] = '\0';
372			break;
373		case 'w':
374			if (wflag)
375				termwidth = UNLIMITED;
376			else if (termwidth < 131)
377				termwidth = 131;
378			wflag++;
379			break;
380		case 'X':
381			/*
382			 * Note that `-X' and `-x' are not standard "selector"
383			 * options. For most selector-options, we check *all*
384			 * processes to see if any are matched by the given
385			 * value(s).  After we have a set of all the matched
386			 * processes, then `-X' and `-x' govern whether we
387			 * modify that *matched* set for processes which do
388			 * not have a controlling terminal.  `-X' causes
389			 * those processes to be deleted from the matched
390			 * set, while `-x' causes them to be kept.
391			 */
392			xkeep = 0;
393			break;
394		case 'x':
395			xkeep = 1;
396			break;
397		case 'Z':
398			parsefmt(Zfmt, 0);
399			Zfmt[0] = '\0';
400			break;
401		case '?':
402		default:
403			usage();
404		}
405	argc -= optind;
406	argv += optind;
407
408	if (optfatal)
409		exit(1);		/* Error messages already printed */
410
411	if (xkeep < 0)			/* Neither -X nor -x was specified */
412		xkeep = xkeep_implied;
413
414#define	BACKWARD_COMPATIBILITY
415#ifdef	BACKWARD_COMPATIBILITY
416	if (*argv) {
417		nlistf = *argv;
418		if (*++argv) {
419			memf = *argv;
420		}
421	}
422#endif
423	/*
424	 * Discard setgid privileges if not the running kernel so that bad
425	 * guys can't print interesting stuff from kernel memory.
426	 */
427	if (dropgid) {
428		setgid(getgid());
429		setuid(getuid());
430	}
431
432	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
433	if (kd == 0)
434		errx(1, "%s", errbuf);
435
436	if (!_fmt)
437		parsefmt(dfmt, 0);
438
439	if (nselectors == 0) {
440		uidlist.ptr = malloc(sizeof(uid_t));
441		if (uidlist.ptr == NULL)
442			errx(1, "malloc failed");
443		nselectors = 1;
444		uidlist.count = uidlist.maxcount = 1;
445		*uidlist.uids = getuid();
446	}
447
448	/*
449	 * scan requested variables, noting what structures are needed,
450	 * and adjusting header widths as appropriate.
451	 */
452	scanvars();
453
454	/*
455	 * Get process list.  If the user requested just one selector-
456	 * option, then kvm_getprocs can be asked to return just those
457	 * processes.  Otherwise, have it return all processes, and
458	 * then this routine will search that full list and select the
459	 * processes which match any of the user's selector-options.
460	 */
461	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
462	flag = 0;
463	if (nselectors == 1) {
464		/* XXX - Apparently there's no KERN_PROC_GID flag. */
465		if (pgrplist.count == 1) {
466			what = KERN_PROC_PGRP | showthreads;
467			flag = *pgrplist.pids;
468			nselectors = 0;
469		} else if (pidlist.count == 1) {
470			what = KERN_PROC_PID | showthreads;
471			flag = *pidlist.pids;
472			nselectors = 0;
473		} else if (ruidlist.count == 1) {
474			what = KERN_PROC_RUID | showthreads;
475			flag = *ruidlist.uids;
476			nselectors = 0;
477#if 0		/* XXX - KERN_PROC_SESSION causes error in kvm_getprocs? */
478		} else if (sesslist.count == 1) {
479			what = KERN_PROC_SESSION | showthreads;
480			flag = *sesslist.pids;
481			nselectors = 0;
482#endif
483		} else if (ttylist.count == 1) {
484			what = KERN_PROC_TTY | showthreads;
485			flag = *ttylist.ttys;
486			nselectors = 0;
487		} else if (uidlist.count == 1) {
488			what = KERN_PROC_UID | showthreads;
489			flag = *uidlist.uids;
490			nselectors = 0;
491		} else if (all) {
492			/* No need for this routine to select processes. */
493			nselectors = 0;
494		}
495	}
496
497	/*
498	 * select procs
499	 */
500	nentries = -1;
501	kp = kvm_getprocs(kd, what, flag, &nentries);
502	if ((kp == 0 && nentries > 0) || (kp != 0 && nentries < 0))
503		errx(1, "%s", kvm_geterr(kd));
504	nkept = 0;
505	if (nentries > 0) {
506		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
507			errx(1, "malloc failed");
508		for (i = nentries; --i >= 0; ++kp) {
509			/*
510			 * If the user specified multiple selection-criteria,
511			 * then keep any process matched by the inclusive OR
512			 * of all the selection-criteria given.
513			 */
514			if (pidlist.count > 0) {
515				for (elem = 0; elem < pidlist.count; elem++)
516					if (kp->ki_pid == pidlist.pids[elem])
517						goto keepit;
518			}
519			/*
520			 * Note that we had to process pidlist before
521			 * filtering out processes which do not have
522			 * a controlling terminal.
523			 */
524			if (xkeep == 0) {
525				if ((kp->ki_tdev == NODEV ||
526				    (kp->ki_flag & P_CONTROLT) == 0))
527					continue;
528			}
529			if (nselectors == 0)
530				goto keepit;
531			if (gidlist.count > 0) {
532				for (elem = 0; elem < gidlist.count; elem++)
533					if (kp->ki_rgid == gidlist.gids[elem])
534						goto keepit;
535			}
536			if (pgrplist.count > 0) {
537				for (elem = 0; elem < pgrplist.count; elem++)
538					if (kp->ki_pgid == pgrplist.pids[elem])
539						goto keepit;
540			}
541			if (ruidlist.count > 0) {
542				for (elem = 0; elem < ruidlist.count; elem++)
543					if (kp->ki_ruid == ruidlist.uids[elem])
544						goto keepit;
545			}
546			if (sesslist.count > 0) {
547				for (elem = 0; elem < sesslist.count; elem++)
548					if (kp->ki_sid == sesslist.pids[elem])
549						goto keepit;
550			}
551			if (ttylist.count > 0) {
552				for (elem = 0; elem < ttylist.count; elem++)
553					if (kp->ki_tdev == ttylist.ttys[elem])
554						goto keepit;
555			}
556			if (uidlist.count > 0) {
557				for (elem = 0; elem < uidlist.count; elem++)
558					if (kp->ki_uid == uidlist.uids[elem])
559						goto keepit;
560			}
561			/*
562			 * This process did not match any of the user's
563			 * selector-options, so skip the process.
564			 */
565			continue;
566
567		keepit:
568			kinfo[nkept].ki_p = kp;
569			if (needuser)
570				saveuser(&kinfo[nkept]);
571			dynsizevars(&kinfo[nkept]);
572			nkept++;
573		}
574	}
575
576	sizevars();
577
578	/*
579	 * print header
580	 */
581	printheader();
582	if (nkept == 0)
583		exit(1);
584
585	/*
586	 * sort proc list
587	 */
588	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
589	/*
590	 * For each process, call each variable output function.
591	 */
592	for (i = lineno = 0; i < nkept; i++) {
593		for (vent = vhead; vent; vent = vent->next) {
594			(vent->var->oproc)(&kinfo[i], vent);
595			if (vent->next != NULL)
596				(void)putchar(' ');
597		}
598		(void)putchar('\n');
599		if (prtheader && lineno++ == prtheader - 4) {
600			(void)putchar('\n');
601			printheader();
602			lineno = 0;
603		}
604	}
605	free_list(&gidlist);
606	free_list(&pidlist);
607	free_list(&pgrplist);
608	free_list(&ruidlist);
609	free_list(&sesslist);
610	free_list(&ttylist);
611	free_list(&uidlist);
612
613	exit(eval);
614}
615
616static int
617addelem_gid(struct listinfo *inf, const char *elem)
618{
619	struct group *grp;
620	const char *nameorID;
621	char *endp;
622	intmax_t ltemp;
623
624	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
625		if (*elem == '\0')
626			warnx("Invalid (zero-length) %s name", inf->lname);
627		else
628			warnx("%s name too long: %s", inf->lname, elem);
629		optfatal = 1;
630		return (0);			/* Do not add this value */
631	}
632
633	/*
634	 * SUSv3 states that `ps -G grouplist' should match "real-group
635	 * ID numbers", and does not mention group-names.  I do want to
636	 * also support group-names, so this tries for a group-id first,
637	 * and only tries for a name if that doesn't work.  This is the
638	 * opposite order of what is done in addelem_uid(), but in
639	 * practice the order would only matter for group-names which
640	 * are all-numeric.
641	 */
642	grp = NULL;
643	nameorID = "named";
644	errno = 0;
645	ltemp = strtol(elem, &endp, 10);
646	if (errno == 0 && *endp == '\0' && ltemp >= 0 && ltemp <= GID_MAX) {
647		nameorID = "name or ID matches";
648		grp = getgrgid((gid_t)ltemp);
649	}
650	if (grp == NULL)
651		grp = getgrnam(elem);
652	if (grp == NULL) {
653		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
654		optfatal = 1;
655		return (0);			/* Do not add this value */
656	}
657
658	if (inf->count >= inf->maxcount)
659		expand_list(inf);
660	inf->gids[(inf->count)++] = grp->gr_gid;
661	return (1);
662}
663
664#define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h */
665static int
666addelem_pid(struct listinfo *inf, const char *elem)
667{
668	char *endp;
669	long tempid;
670
671	if (*elem == '\0')
672		tempid = 0L;
673	else {
674		errno = 0;
675		tempid = strtol(elem, &endp, 10);
676		if (*endp != '\0' || tempid < 0 || elem == endp) {
677			warnx("Invalid %s: %s", inf->lname, elem);
678			errno = ERANGE;
679		} else if (errno != 0 || tempid > BSD_PID_MAX) {
680			warnx("%s too large: %s", inf->lname, elem);
681			errno = ERANGE;
682		}
683		if (errno == ERANGE) {
684			optfatal = 1;
685			return (0);		/* Do not add this value */
686		}
687	}
688
689	if (inf->count >= inf->maxcount)
690		expand_list(inf);
691	inf->pids[(inf->count)++] = tempid;
692	return (1);
693}
694#undef	BSD_PID_MAX
695
696static int
697addelem_tty(struct listinfo *inf, const char *elem)
698{
699	const char *ttypath;
700	struct stat sb;
701	char pathbuf[PATH_MAX];
702
703	if (strcmp(elem, "co") == 0)
704		ttypath = strdup(_PATH_CONSOLE);
705	else if (*elem == '/')
706		ttypath = elem;
707	else {
708		strlcpy(pathbuf, _PATH_TTY, sizeof(pathbuf));
709		strlcat(pathbuf, elem, sizeof(pathbuf));
710		ttypath = pathbuf;
711	}
712
713	if (stat(ttypath, &sb) == -1) {
714		warn("%s", ttypath);
715		optfatal = 1;
716		return (0);			/* Do not add this value */
717	}
718	if (!S_ISCHR(sb.st_mode)) {
719		warn("%s: Not a terminal", ttypath);
720		optfatal = 1;
721		return (0);			/* Do not add this value */
722	}
723
724	if (inf->count >= inf->maxcount)
725		expand_list(inf);
726	inf->ttys[(inf->count)++] = sb.st_rdev;
727	return (1);
728}
729
730static int
731addelem_uid(struct listinfo *inf, const char *elem)
732{
733	struct passwd *pwd;
734	char *endp;
735	intmax_t ltemp;
736
737	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
738		if (*elem == '\0')
739			warnx("Invalid (zero-length) %s name", inf->lname);
740		else
741			warnx("%s name too long: %s", inf->lname, elem);
742		optfatal = 1;
743		return (0);			/* Do not add this value */
744	}
745
746	pwd = getpwnam(elem);
747	if (pwd == NULL) {
748		errno = 0;
749		ltemp = strtol(elem, &endp, 10);
750		if (errno != 0 || *endp != '\0' || ltemp < 0 ||
751		    ltemp > UID_MAX)
752			warnx("No %s named '%s'", inf->lname, elem);
753		else {
754			/* The string is all digits, so it might be a userID. */
755			pwd = getpwuid((uid_t)ltemp);
756			if (pwd == NULL)
757				warnx("No %s name or ID matches '%s'",
758				    inf->lname, elem);
759		}
760	}
761	if (pwd == NULL) {
762		/*
763		 * These used to be treated as minor warnings (and the
764		 * option was simply ignored), but now they are fatal
765		 * errors (and the command will be aborted).
766		 */
767		optfatal = 1;
768		return (0);			/* Do not add this value */
769	}
770
771	if (inf->count >= inf->maxcount)
772		expand_list(inf);
773	inf->uids[(inf->count)++] = pwd->pw_uid;
774	return (1);
775}
776
777static void
778add_list(struct listinfo *inf, const char *argp)
779{
780	const char *savep;
781	char *cp, *endp;
782	int toolong;
783	char elemcopy[PATH_MAX];
784
785	while (*argp != '\0') {
786		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
787			argp++;
788		savep = argp;
789		toolong = 0;
790		cp = elemcopy;
791		if (strchr(T_SEP, *argp) == NULL) {
792			endp = elemcopy + sizeof(elemcopy) - 1;
793			while (*argp != '\0' && cp <= endp &&
794			    strchr(W_SEP T_SEP, *argp) == NULL)
795				*cp++ = *argp++;
796			if (cp > endp)
797				toolong = 1;
798		}
799		if (!toolong) {
800			*cp = '\0';
801#ifndef ADD_PS_LISTRESET
802	/* This is how the standard expects lists to be handled. */
803			inf->addelem(inf, elemcopy);
804#else
805	/*
806	 * This would add a simple non-standard-but-convienent feature.
807	 *
808	 * XXX - Adding this check increased the total size of `ps' by
809	 *	3940 bytes on i386!  That's 12% of the entire program!
810	 *	The `ps.o' file grew by only about 40 bytes, but the
811	 *	final (stripped) executable in /bin/ps grew by 12%.
812	 */
813			/*
814			 * We now have a single element.  Add it to the
815			 * list, unless the element is ":".  In that case,
816			 * reset the list so previous entries are ignored.
817			 */
818			if (strcmp(elemcopy, ":") == 0)
819				inf->count = 0;
820			else
821				inf->addelem(inf, elemcopy);
822#endif
823		} else {
824			/*
825			 * The string is too long to copy.  Find the end
826			 * of the string to print out the warning message.
827			 */
828			while (*argp != '\0' && strchr(W_SEP T_SEP,
829			    *argp) == NULL)
830				argp++;
831			warnx("Value too long: %.*s", (int)(argp - savep),
832			    savep);
833			optfatal = 1;
834		}
835		/*
836		 * Skip over any number of trailing whitespace characters,
837		 * but only one (at most) trailing element-terminating
838		 * character.
839		 */
840		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
841			argp++;
842		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
843			argp++;
844			/* Catch case where string ended with a comma. */
845			if (*argp == '\0')
846				inf->addelem(inf, argp);
847		}
848	}
849}
850
851static void *
852expand_list(struct listinfo *inf)
853{
854	void *newlist;
855	int newmax;
856
857	newmax = (inf->maxcount + 1) << 1;
858	newlist = realloc(inf->ptr, newmax * inf->elemsize);
859	if (newlist == NULL) {
860		free(inf->ptr);
861		errx(1, "realloc to %d %ss failed", newmax,
862		    inf->lname);
863	}
864	inf->maxcount = newmax;
865	inf->ptr = newlist;
866
867	return (newlist);
868}
869
870static void
871free_list(struct listinfo *inf)
872{
873
874	inf->count = inf->elemsize = inf->maxcount = 0;
875	if (inf->ptr != NULL)
876		free(inf->ptr);
877	inf->addelem = NULL;
878	inf->lname = NULL;
879	inf->ptr = NULL;
880}
881
882static void
883init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
884    const char *lname)
885{
886
887	inf->count = inf->maxcount = 0;
888	inf->elemsize = elemsize;
889	inf->addelem = artn;
890	inf->lname = lname;
891	inf->ptr = NULL;
892}
893
894VARENT *
895find_varentry(VAR *v)
896{
897	struct varent *vent;
898
899	for (vent = vhead; vent; vent = vent->next) {
900		if (strcmp(vent->var->name, v->name) == 0)
901			return vent;
902	}
903	return NULL;
904}
905
906static void
907scanvars(void)
908{
909	struct varent *vent;
910	VAR *v;
911
912	for (vent = vhead; vent; vent = vent->next) {
913		v = vent->var;
914		if (v->flag & DSIZ) {
915			v->dwidth = v->width;
916			v->width = 0;
917		}
918		if (v->flag & USER)
919			needuser = 1;
920		if (v->flag & COMM)
921			needcomm = 1;
922	}
923}
924
925static void
926dynsizevars(KINFO *ki)
927{
928	struct varent *vent;
929	VAR *v;
930	int i;
931
932	for (vent = vhead; vent; vent = vent->next) {
933		v = vent->var;
934		if (!(v->flag & DSIZ))
935			continue;
936		i = (v->sproc)( ki);
937		if (v->width < i)
938			v->width = i;
939		if (v->width > v->dwidth)
940			v->width = v->dwidth;
941	}
942}
943
944static void
945sizevars(void)
946{
947	struct varent *vent;
948	VAR *v;
949	int i;
950
951	for (vent = vhead; vent; vent = vent->next) {
952		v = vent->var;
953		i = strlen(vent->header);
954		if (v->width < i)
955			v->width = i;
956		totwidth += v->width + 1;	/* +1 for space */
957	}
958	totwidth--;
959}
960
961static const char *
962fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
963  char *comm, int maxlen)
964{
965	const char *s;
966
967	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
968	return (s);
969}
970
971#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
972
973static void
974saveuser(KINFO *ki)
975{
976
977	if (ki->ki_p->ki_sflag & PS_INMEM) {
978		/*
979		 * The u-area might be swapped out, and we can't get
980		 * at it because we have a crashdump and no swap.
981		 * If it's here fill in these fields, otherwise, just
982		 * leave them 0.
983		 */
984		ki->ki_valid = 1;
985	} else
986		ki->ki_valid = 0;
987	/*
988	 * save arguments if needed
989	 */
990	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
991		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
992		    MAXCOMLEN));
993	} else if (needcomm) {
994		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
995	} else {
996		ki->ki_args = NULL;
997	}
998	if (needenv && UREADOK(ki)) {
999		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
1000	} else if (needenv) {
1001		ki->ki_env = malloc(3);
1002		strcpy(ki->ki_env, "()");
1003	} else {
1004		ki->ki_env = NULL;
1005	}
1006}
1007
1008static int
1009pscomp(const void *a, const void *b)
1010{
1011	int i;
1012#define VSIZE(k) ((k)->ki_p->ki_dsize + (k)->ki_p->ki_ssize + \
1013		  (k)->ki_p->ki_tsize)
1014
1015	if (sortby == SORTCPU)
1016		return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
1017	if (sortby == SORTMEM)
1018		return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
1019	i =  (int)((const KINFO *)a)->ki_p->ki_tdev -
1020	    (int)((const KINFO *)b)->ki_p->ki_tdev;
1021	if (i == 0)
1022		i = ((const KINFO *)a)->ki_p->ki_pid -
1023		    ((const KINFO *)b)->ki_p->ki_pid;
1024	return (i);
1025}
1026
1027/*
1028 * ICK (all for getopt), would rather hide the ugliness
1029 * here than taint the main code.
1030 *
1031 *  ps foo -> ps -foo
1032 *  ps 34 -> ps -p34
1033 *
1034 * The old convention that 't' with no trailing tty arg means the users
1035 * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1036 * feature is available with the option 'T', which takes no argument.
1037 */
1038static char *
1039kludge_oldps_options(char *s)
1040{
1041	int have_fmt;
1042	size_t len;
1043	char *newopts, *ns, *cp;
1044
1045	/*
1046	 * If we have an 'o' option, then note it, since we don't want to do
1047	 * some types of munging.
1048	 */
1049	have_fmt = index(s, 'o') != NULL;
1050
1051	len = strlen(s);
1052	if ((newopts = ns = malloc(len + 2)) == NULL)
1053		errx(1, "malloc failed");
1054	/*
1055	 * options begin with '-'
1056	 */
1057	if (*s != '-')
1058		*ns++ = '-';	/* add option flag */
1059	/*
1060	 * gaze to end of argv[1]
1061	 */
1062	cp = s + len - 1;
1063	/*
1064	 * if last letter is a 't' flag with no argument (in the context
1065	 * of the oldps options -- option string NOT starting with a '-' --
1066	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1067	 *
1068	 * However, if a flag accepting a string argument is found in the
1069	 * option string, the remainder of the string is the argument to
1070	 * that flag; do not modify that argument.
1071	 */
1072	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
1073		*cp = 'T';
1074	else {
1075		/*
1076		 * otherwise check for trailing number, which *may* be a
1077		 * pid.
1078		 */
1079		while (cp >= s && isdigit(*cp))
1080			--cp;
1081	}
1082	cp++;
1083	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
1084	ns += cp - s;
1085	/*
1086	 * if there's a trailing number, and not a preceding 'p' (pid) or
1087	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
1088	 */
1089	if (isdigit(*cp) &&
1090	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
1091	    (cp - 1 == s || cp[-2] != 't') && !have_fmt)
1092		*ns++ = 'p';
1093	(void)strcpy(ns, cp);		/* and append the number */
1094
1095	return (newopts);
1096}
1097
1098static void
1099usage(void)
1100{
1101#define	SINGLE_OPTS	"[-aC" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1102
1103	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1104	    "usage: ps " SINGLE_OPTS " [-G gid[,gid]] [-O|o fmt]",
1105	    "          [-p pid[,pid]] [-t tty[,tty]] [-U user[,user]]",
1106	    "          [-M core] [-N system]",
1107	    "       ps [-L]");
1108	exit(1);
1109}
1110