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