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