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