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