ps.c revision 195830
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 195830 2009-07-23 10:20:12Z brian $");
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#include <sys/mount.h>
59
60#include <ctype.h>
61#include <err.h>
62#include <errno.h>
63#include <fcntl.h>
64#include <grp.h>
65#include <kvm.h>
66#include <limits.h>
67#include <locale.h>
68#include <paths.h>
69#include <pwd.h>
70#include <stdio.h>
71#include <stdlib.h>
72#include <string.h>
73#include <unistd.h>
74
75#include "ps.h"
76
77#define	_PATH_PTS	"/dev/pts/"
78
79#define	W_SEP	" \t"		/* "Whitespace" list separators */
80#define	T_SEP	","		/* "Terminate-element" list separators */
81
82#ifdef LAZY_PS
83#define	DEF_UREAD	0
84#define	OPT_LAZY_f	"f"
85#else
86#define	DEF_UREAD	1	/* Always do the more-expensive read. */
87#define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
88#endif
89
90/*
91 * isdigit takes an `int', but expects values in the range of unsigned char.
92 * This wrapper ensures that values from a 'char' end up in the correct range.
93 */
94#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
95
96int	 cflag;			/* -c */
97int	 eval;			/* Exit value */
98time_t	 now;			/* Current time(3) value */
99int	 rawcpu;		/* -C */
100int	 sumrusage;		/* -S */
101int	 termwidth;		/* Width of the screen (0 == infinity). */
102int	 totwidth;		/* Calculated-width of requested variables. */
103int	 showthreads;		/* will threads be shown? */
104
105struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
106
107static int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
108static kvm_t	*kd;
109static KINFO	*kinfo;
110static int	 needcomm;	/* -o "command" */
111static int	 needenv;	/* -e */
112static int	 needuser;	/* -o "user" */
113static int	 optfatal;	/* Fatal error parsing some list-option. */
114
115static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
116
117struct listinfo;
118typedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
119
120struct listinfo {
121	int		 count;
122	int		 maxcount;
123	int		 elemsize;
124	addelem_rtn	*addelem;
125	const char	*lname;
126	union {
127		gid_t	*gids;
128		pid_t	*pids;
129		dev_t	*ttys;
130		uid_t	*uids;
131		void	*ptr;
132	} l;
133};
134
135static int	 check_procfs(void);
136static int	 addelem_gid(struct listinfo *, const char *);
137static int	 addelem_pid(struct listinfo *, const char *);
138static int	 addelem_tty(struct listinfo *, const char *);
139static int	 addelem_uid(struct listinfo *, const char *);
140static void	 add_list(struct listinfo *, const char *);
141static void	 descendant_sort(KINFO *, int);
142static void	 dynsizevars(KINFO *);
143static void	*expand_list(struct listinfo *);
144static const char *
145		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
146		    KINFO *, char *, int);
147static void	 free_list(struct listinfo *);
148static void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
149static char	*kludge_oldps_options(const char *, char *, const char *);
150static int	 pscomp(const void *, const void *);
151static void	 saveuser(KINFO *);
152static void	 scanvars(void);
153static void	 sizevars(void);
154static void	 usage(void);
155
156static char dfmt[] = "pid,tt,state,time,command";
157static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
158static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
159			"tt,time,command";
160static char   o1[] = "pid";
161static char   o2[] = "tt,state,time,command";
162static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
163static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
164			"%cpu,%mem,command";
165static char Zfmt[] = "label";
166
167#define	PS_ARGS	"AaCcde" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
168
169int
170main(int argc, char *argv[])
171{
172	struct listinfo gidlist, pgrplist, pidlist;
173	struct listinfo ruidlist, sesslist, ttylist, uidlist;
174	struct kinfo_proc *kp;
175	KINFO *next_KINFO;
176	struct varent *vent;
177	struct winsize ws;
178	const char *nlistf, *memf;
179	char *cols;
180	int all, ch, elem, flag, _fmt, i, lineno;
181	int descendancy, nentries, nkept, nselectors;
182	int prtheader, wflag, what, xkeep, xkeep_implied;
183	char errbuf[_POSIX2_LINE_MAX];
184
185	(void) setlocale(LC_ALL, "");
186	time(&now);			/* Used by routines in print.c. */
187
188	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
189		termwidth = atoi(cols);
190	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
191	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
192	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
193	     ws.ws_col == 0)
194		termwidth = 79;
195	else
196		termwidth = ws.ws_col - 1;
197
198	/*
199	 * Hide a number of option-processing kludges in a separate routine,
200	 * to support some historical BSD behaviors, such as `ps axu'.
201	 */
202	if (argc > 1)
203		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
204
205	all = descendancy = _fmt = nselectors = optfatal = 0;
206	prtheader = showthreads = wflag = xkeep_implied = 0;
207	xkeep = -1;			/* Neither -x nor -X. */
208	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
209	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
210	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
211	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
212	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
213	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
214	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
215	memf = nlistf = _PATH_DEVNULL;
216	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
217		switch (ch) {
218		case 'A':
219			/*
220			 * Exactly the same as `-ax'.   This has been
221			 * added for compatability with SUSv3, but for
222			 * now it will not be described in the man page.
223			 */
224			nselectors++;
225			all = xkeep = 1;
226			break;
227		case 'a':
228			nselectors++;
229			all = 1;
230			break;
231		case 'C':
232			rawcpu = 1;
233			break;
234		case 'c':
235			cflag = 1;
236			break;
237		case 'd':
238			descendancy = 1;
239			break;
240		case 'e':			/* XXX set ufmt */
241			needenv = 1;
242			break;
243#ifdef LAZY_PS
244		case 'f':
245			if (getuid() == 0 || getgid() == 0)
246				forceuread = 1;
247			break;
248#endif
249		case 'G':
250			add_list(&gidlist, optarg);
251			xkeep_implied = 1;
252			nselectors++;
253			break;
254		case 'g':
255#if 0
256			/*-
257			 * XXX - This SUSv3 behavior is still under debate
258			 *	since it conflicts with the (undocumented)
259			 *	`-g' option.  So we skip it for now.
260			 */
261			add_list(&pgrplist, optarg);
262			xkeep_implied = 1;
263			nselectors++;
264			break;
265#else
266			/* The historical BSD-ish (from SunOS) behavior. */
267			break;			/* no-op */
268#endif
269		case 'H':
270			showthreads = KERN_PROC_INC_THREAD;
271			break;
272		case 'h':
273			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
274			break;
275		case 'j':
276			parsefmt(jfmt, 0);
277			_fmt = 1;
278			jfmt[0] = '\0';
279			break;
280		case 'L':
281			showkey();
282			exit(0);
283		case 'l':
284			parsefmt(lfmt, 0);
285			_fmt = 1;
286			lfmt[0] = '\0';
287			break;
288		case 'M':
289			memf = optarg;
290			break;
291		case 'm':
292			sortby = SORTMEM;
293			break;
294		case 'N':
295			nlistf = optarg;
296			break;
297		case 'O':
298			parsefmt(o1, 1);
299			parsefmt(optarg, 1);
300			parsefmt(o2, 1);
301			o1[0] = o2[0] = '\0';
302			_fmt = 1;
303			break;
304		case 'o':
305			parsefmt(optarg, 1);
306			_fmt = 1;
307			break;
308		case 'p':
309			add_list(&pidlist, optarg);
310			/*
311			 * Note: `-p' does not *set* xkeep, but any values
312			 * from pidlist are checked before xkeep is.  That
313			 * way they are always matched, even if the user
314			 * specifies `-X'.
315			 */
316			nselectors++;
317			break;
318#if 0
319		case 'R':
320			/*-
321			 * XXX - This un-standard option is still under
322			 *	debate.  This is what SUSv3 defines as
323			 *	the `-U' option, and while it would be
324			 *	nice to have, it could cause even more
325			 *	confusion to implement it as `-R'.
326			 */
327			add_list(&ruidlist, optarg);
328			xkeep_implied = 1;
329			nselectors++;
330			break;
331#endif
332		case 'r':
333			sortby = SORTCPU;
334			break;
335		case 'S':
336			sumrusage = 1;
337			break;
338#if 0
339		case 's':
340			/*-
341			 * XXX - This non-standard option is still under
342			 *	debate.  This *is* supported on Solaris,
343			 *	Linux, and IRIX, but conflicts with `-s'
344			 *	on NetBSD and maybe some older BSD's.
345			 */
346			add_list(&sesslist, optarg);
347			xkeep_implied = 1;
348			nselectors++;
349			break;
350#endif
351		case 'T':
352			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
353				errx(1, "stdin: not a terminal");
354			/* FALLTHROUGH */
355		case 't':
356			add_list(&ttylist, optarg);
357			xkeep_implied = 1;
358			nselectors++;
359			break;
360		case 'U':
361			/* This is what SUSv3 defines as the `-u' option. */
362			add_list(&uidlist, optarg);
363			xkeep_implied = 1;
364			nselectors++;
365			break;
366		case 'u':
367			parsefmt(ufmt, 0);
368			sortby = SORTCPU;
369			_fmt = 1;
370			ufmt[0] = '\0';
371			break;
372		case 'v':
373			parsefmt(vfmt, 0);
374			sortby = SORTMEM;
375			_fmt = 1;
376			vfmt[0] = '\0';
377			break;
378		case 'w':
379			if (wflag)
380				termwidth = UNLIMITED;
381			else if (termwidth < 131)
382				termwidth = 131;
383			wflag++;
384			break;
385		case 'X':
386			/*
387			 * Note that `-X' and `-x' are not standard "selector"
388			 * options. For most selector-options, we check *all*
389			 * processes to see if any are matched by the given
390			 * value(s).  After we have a set of all the matched
391			 * processes, then `-X' and `-x' govern whether we
392			 * modify that *matched* set for processes which do
393			 * not have a controlling terminal.  `-X' causes
394			 * those processes to be deleted from the matched
395			 * set, while `-x' causes them to be kept.
396			 */
397			xkeep = 0;
398			break;
399		case 'x':
400			xkeep = 1;
401			break;
402		case 'Z':
403			parsefmt(Zfmt, 0);
404			Zfmt[0] = '\0';
405			break;
406		case '?':
407		default:
408			usage();
409		}
410	argc -= optind;
411	argv += optind;
412
413	/*
414	 * If the user specified ps -e then they want a copy of the process
415	 * environment kvm_getenvv(3) attempts to open /proc/<pid>/mem.
416	 * Check to make sure that procfs is mounted on /proc, otherwise
417	 * print a warning informing the user that output will be incomplete.
418	 */
419	if (needenv == 1 && check_procfs() == 0)
420		warnx("Process environment requires procfs(5)");
421	/*
422	 * If there arguments after processing all the options, attempt
423	 * to treat them as a list of process ids.
424	 */
425	while (*argv) {
426		if (!isdigitch(**argv))
427			break;
428		add_list(&pidlist, *argv);
429		argv++;
430	}
431	if (*argv) {
432		fprintf(stderr, "%s: illegal argument: %s\n",
433		    getprogname(), *argv);
434		usage();
435	}
436	if (optfatal)
437		exit(1);		/* Error messages already printed. */
438	if (xkeep < 0)			/* Neither -X nor -x was specified. */
439		xkeep = xkeep_implied;
440
441	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
442	if (kd == 0)
443		errx(1, "%s", errbuf);
444
445	if (!_fmt)
446		parsefmt(dfmt, 0);
447
448	if (nselectors == 0) {
449		uidlist.l.ptr = malloc(sizeof(uid_t));
450		if (uidlist.l.ptr == NULL)
451			errx(1, "malloc failed");
452		nselectors = 1;
453		uidlist.count = uidlist.maxcount = 1;
454		*uidlist.l.uids = getuid();
455	}
456
457	/*
458	 * scan requested variables, noting what structures are needed,
459	 * and adjusting header widths as appropriate.
460	 */
461	scanvars();
462
463	/*
464	 * Get process list.  If the user requested just one selector-
465	 * option, then kvm_getprocs can be asked to return just those
466	 * processes.  Otherwise, have it return all processes, and
467	 * then this routine will search that full list and select the
468	 * processes which match any of the user's selector-options.
469	 */
470	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
471	flag = 0;
472	if (nselectors == 1) {
473		if (gidlist.count == 1) {
474			what = KERN_PROC_RGID | showthreads;
475			flag = *gidlist.l.gids;
476			nselectors = 0;
477		} else if (pgrplist.count == 1) {
478			what = KERN_PROC_PGRP | showthreads;
479			flag = *pgrplist.l.pids;
480			nselectors = 0;
481		} else if (pidlist.count == 1) {
482			what = KERN_PROC_PID | showthreads;
483			flag = *pidlist.l.pids;
484			nselectors = 0;
485		} else if (ruidlist.count == 1) {
486			what = KERN_PROC_RUID | showthreads;
487			flag = *ruidlist.l.uids;
488			nselectors = 0;
489		} else if (sesslist.count == 1) {
490			what = KERN_PROC_SESSION | showthreads;
491			flag = *sesslist.l.pids;
492			nselectors = 0;
493		} else if (ttylist.count == 1) {
494			what = KERN_PROC_TTY | showthreads;
495			flag = *ttylist.l.ttys;
496			nselectors = 0;
497		} else if (uidlist.count == 1) {
498			what = KERN_PROC_UID | showthreads;
499			flag = *uidlist.l.uids;
500			nselectors = 0;
501		} else if (all) {
502			/* No need for this routine to select processes. */
503			nselectors = 0;
504		}
505	}
506
507	/*
508	 * select procs
509	 */
510	nentries = -1;
511	kp = kvm_getprocs(kd, what, flag, &nentries);
512	if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
513		errx(1, "%s", kvm_geterr(kd));
514	nkept = 0;
515	if (nentries > 0) {
516		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
517			errx(1, "malloc failed");
518		for (i = nentries; --i >= 0; ++kp) {
519			/*
520			 * If the user specified multiple selection-criteria,
521			 * then keep any process matched by the inclusive OR
522			 * of all the selection-criteria given.
523			 */
524			if (pidlist.count > 0) {
525				for (elem = 0; elem < pidlist.count; elem++)
526					if (kp->ki_pid == pidlist.l.pids[elem])
527						goto keepit;
528			}
529			/*
530			 * Note that we had to process pidlist before
531			 * filtering out processes which do not have
532			 * a controlling terminal.
533			 */
534			if (xkeep == 0) {
535				if ((kp->ki_tdev == NODEV ||
536				    (kp->ki_flag & P_CONTROLT) == 0))
537					continue;
538			}
539			if (nselectors == 0)
540				goto keepit;
541			if (gidlist.count > 0) {
542				for (elem = 0; elem < gidlist.count; elem++)
543					if (kp->ki_rgid == gidlist.l.gids[elem])
544						goto keepit;
545			}
546			if (pgrplist.count > 0) {
547				for (elem = 0; elem < pgrplist.count; elem++)
548					if (kp->ki_pgid ==
549					    pgrplist.l.pids[elem])
550						goto keepit;
551			}
552			if (ruidlist.count > 0) {
553				for (elem = 0; elem < ruidlist.count; elem++)
554					if (kp->ki_ruid ==
555					    ruidlist.l.uids[elem])
556						goto keepit;
557			}
558			if (sesslist.count > 0) {
559				for (elem = 0; elem < sesslist.count; elem++)
560					if (kp->ki_sid == sesslist.l.pids[elem])
561						goto keepit;
562			}
563			if (ttylist.count > 0) {
564				for (elem = 0; elem < ttylist.count; elem++)
565					if (kp->ki_tdev == ttylist.l.ttys[elem])
566						goto keepit;
567			}
568			if (uidlist.count > 0) {
569				for (elem = 0; elem < uidlist.count; elem++)
570					if (kp->ki_uid == uidlist.l.uids[elem])
571						goto keepit;
572			}
573			/*
574			 * This process did not match any of the user's
575			 * selector-options, so skip the process.
576			 */
577			continue;
578
579		keepit:
580			next_KINFO = &kinfo[nkept];
581			next_KINFO->ki_p = kp;
582			next_KINFO->ki_d.level = 0;
583			next_KINFO->ki_d.prefix = NULL;
584			next_KINFO->ki_pcpu = getpcpu(next_KINFO);
585			if (sortby == SORTMEM)
586				next_KINFO->ki_memsize = kp->ki_tsize +
587				    kp->ki_dsize + kp->ki_ssize;
588			if (needuser)
589				saveuser(next_KINFO);
590			dynsizevars(next_KINFO);
591			nkept++;
592		}
593	}
594
595	sizevars();
596
597	/*
598	 * print header
599	 */
600	printheader();
601	if (nkept == 0)
602		exit(1);
603
604	/*
605	 * sort proc list
606	 */
607	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
608
609	/*
610	 * We want things in descendant order
611	 */
612	if (descendancy)
613		descendant_sort(kinfo, nkept);
614
615	/*
616	 * For each process, call each variable output function.
617	 */
618	for (i = lineno = 0; i < nkept; i++) {
619		STAILQ_FOREACH(vent, &varlist, next_ve) {
620			(vent->var->oproc)(&kinfo[i], vent);
621			if (STAILQ_NEXT(vent, next_ve) != NULL)
622				(void)putchar(' ');
623		}
624		(void)putchar('\n');
625		if (prtheader && lineno++ == prtheader - 4) {
626			(void)putchar('\n');
627			printheader();
628			lineno = 0;
629		}
630	}
631	free_list(&gidlist);
632	free_list(&pidlist);
633	free_list(&pgrplist);
634	free_list(&ruidlist);
635	free_list(&sesslist);
636	free_list(&ttylist);
637	free_list(&uidlist);
638	for (i = 0; i < nkept; i++)
639		free(kinfo[i].ki_d.prefix);
640	free(kinfo);
641
642	exit(eval);
643}
644
645static int
646addelem_gid(struct listinfo *inf, const char *elem)
647{
648	struct group *grp;
649	const char *nameorID;
650	char *endp;
651	u_long bigtemp;
652
653	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
654		if (*elem == '\0')
655			warnx("Invalid (zero-length) %s name", inf->lname);
656		else
657			warnx("%s name too long: %s", inf->lname, elem);
658		optfatal = 1;
659		return (0);		/* Do not add this value. */
660	}
661
662	/*
663	 * SUSv3 states that `ps -G grouplist' should match "real-group
664	 * ID numbers", and does not mention group-names.  I do want to
665	 * also support group-names, so this tries for a group-id first,
666	 * and only tries for a name if that doesn't work.  This is the
667	 * opposite order of what is done in addelem_uid(), but in
668	 * practice the order would only matter for group-names which
669	 * are all-numeric.
670	 */
671	grp = NULL;
672	nameorID = "named";
673	errno = 0;
674	bigtemp = strtoul(elem, &endp, 10);
675	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
676		nameorID = "name or ID matches";
677		grp = getgrgid((gid_t)bigtemp);
678	}
679	if (grp == NULL)
680		grp = getgrnam(elem);
681	if (grp == NULL) {
682		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
683		optfatal = 1;
684		return (0);
685	}
686	if (inf->count >= inf->maxcount)
687		expand_list(inf);
688	inf->l.gids[(inf->count)++] = grp->gr_gid;
689	return (1);
690}
691
692#define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h. */
693static int
694addelem_pid(struct listinfo *inf, const char *elem)
695{
696	char *endp;
697	long tempid;
698
699	if (*elem == '\0') {
700		warnx("Invalid (zero-length) process id");
701		optfatal = 1;
702		return (0);		/* Do not add this value. */
703	}
704
705	errno = 0;
706	tempid = strtol(elem, &endp, 10);
707	if (*endp != '\0' || tempid < 0 || elem == endp) {
708		warnx("Invalid %s: %s", inf->lname, elem);
709		errno = ERANGE;
710	} else if (errno != 0 || tempid > BSD_PID_MAX) {
711		warnx("%s too large: %s", inf->lname, elem);
712		errno = ERANGE;
713	}
714	if (errno == ERANGE) {
715		optfatal = 1;
716		return (0);
717	}
718	if (inf->count >= inf->maxcount)
719		expand_list(inf);
720	inf->l.pids[(inf->count)++] = tempid;
721	return (1);
722}
723#undef	BSD_PID_MAX
724
725/*-
726 * The user can specify a device via one of three formats:
727 *     1) fully qualified, e.g.:     /dev/ttyp0 /dev/console	/dev/pts/0
728 *     2) missing "/dev", e.g.:      ttyp0      console		pts/0
729 *     3) two-letters, e.g.:         p0         co		0
730 *        (matching letters that would be seen in the "TT" column)
731 */
732static int
733addelem_tty(struct listinfo *inf, const char *elem)
734{
735	const char *ttypath;
736	struct stat sb;
737	char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
738
739	ttypath = NULL;
740	pathbuf2[0] = '\0';
741	pathbuf3[0] = '\0';
742	switch (*elem) {
743	case '/':
744		ttypath = elem;
745		break;
746	case 'c':
747		if (strcmp(elem, "co") == 0) {
748			ttypath = _PATH_CONSOLE;
749			break;
750		}
751		/* FALLTHROUGH */
752	default:
753		strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
754		strlcat(pathbuf, elem, sizeof(pathbuf));
755		ttypath = pathbuf;
756		if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
757			break;
758		if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
759			break;
760		if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
761			break;
762		/* Check to see if /dev/tty${elem} exists */
763		strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
764		strlcat(pathbuf2, elem, sizeof(pathbuf2));
765		if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
766			/* No need to repeat stat() && S_ISCHR() checks */
767			ttypath = NULL;
768			break;
769		}
770		/* Check to see if /dev/pts/${elem} exists */
771		strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
772		strlcat(pathbuf3, elem, sizeof(pathbuf3));
773		if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
774			/* No need to repeat stat() && S_ISCHR() checks */
775			ttypath = NULL;
776			break;
777		}
778		break;
779	}
780	if (ttypath) {
781		if (stat(ttypath, &sb) == -1) {
782			if (pathbuf3[0] != '\0')
783				warn("%s, %s, and %s", pathbuf3, pathbuf2,
784				    ttypath);
785			else
786				warn("%s", ttypath);
787			optfatal = 1;
788			return (0);
789		}
790		if (!S_ISCHR(sb.st_mode)) {
791			if (pathbuf3[0] != '\0')
792				warnx("%s, %s, and %s: Not a terminal",
793				    pathbuf3, pathbuf2, ttypath);
794			else
795				warnx("%s: Not a terminal", ttypath);
796			optfatal = 1;
797			return (0);
798		}
799	}
800	if (inf->count >= inf->maxcount)
801		expand_list(inf);
802	inf->l.ttys[(inf->count)++] = sb.st_rdev;
803	return (1);
804}
805
806static int
807addelem_uid(struct listinfo *inf, const char *elem)
808{
809	struct passwd *pwd;
810	char *endp;
811	u_long bigtemp;
812
813	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
814		if (*elem == '\0')
815			warnx("Invalid (zero-length) %s name", inf->lname);
816		else
817			warnx("%s name too long: %s", inf->lname, elem);
818		optfatal = 1;
819		return (0);		/* Do not add this value. */
820	}
821
822	pwd = getpwnam(elem);
823	if (pwd == NULL) {
824		errno = 0;
825		bigtemp = strtoul(elem, &endp, 10);
826		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
827			warnx("No %s named '%s'", inf->lname, elem);
828		else {
829			/* The string is all digits, so it might be a userID. */
830			pwd = getpwuid((uid_t)bigtemp);
831			if (pwd == NULL)
832				warnx("No %s name or ID matches '%s'",
833				    inf->lname, elem);
834		}
835	}
836	if (pwd == NULL) {
837		/*
838		 * These used to be treated as minor warnings (and the
839		 * option was simply ignored), but now they are fatal
840		 * errors (and the command will be aborted).
841		 */
842		optfatal = 1;
843		return (0);
844	}
845	if (inf->count >= inf->maxcount)
846		expand_list(inf);
847	inf->l.uids[(inf->count)++] = pwd->pw_uid;
848	return (1);
849}
850
851static void
852add_list(struct listinfo *inf, const char *argp)
853{
854	const char *savep;
855	char *cp, *endp;
856	int toolong;
857	char elemcopy[PATH_MAX];
858
859	if (*argp == 0)
860		inf->addelem(inf, elemcopy);
861	while (*argp != '\0') {
862		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
863			argp++;
864		savep = argp;
865		toolong = 0;
866		cp = elemcopy;
867		if (strchr(T_SEP, *argp) == NULL) {
868			endp = elemcopy + sizeof(elemcopy) - 1;
869			while (*argp != '\0' && cp <= endp &&
870			    strchr(W_SEP T_SEP, *argp) == NULL)
871				*cp++ = *argp++;
872			if (cp > endp)
873				toolong = 1;
874		}
875		if (!toolong) {
876			*cp = '\0';
877			/*
878			 * Add this single element to the given list.
879			 */
880			inf->addelem(inf, elemcopy);
881		} else {
882			/*
883			 * The string is too long to copy.  Find the end
884			 * of the string to print out the warning message.
885			 */
886			while (*argp != '\0' && strchr(W_SEP T_SEP,
887			    *argp) == NULL)
888				argp++;
889			warnx("Value too long: %.*s", (int)(argp - savep),
890			    savep);
891			optfatal = 1;
892		}
893		/*
894		 * Skip over any number of trailing whitespace characters,
895		 * but only one (at most) trailing element-terminating
896		 * character.
897		 */
898		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
899			argp++;
900		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
901			argp++;
902			/* Catch case where string ended with a comma. */
903			if (*argp == '\0')
904				inf->addelem(inf, argp);
905		}
906	}
907}
908
909static void
910descendant_sort(KINFO *ki, int items)
911{
912	int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
913	unsigned char *path;
914	KINFO kn;
915
916	/*
917	 * First, sort the entries by descendancy, tracking the descendancy
918	 * depth in the ki_d.level field.
919	 */
920	src = 0;
921	maxlvl = 0;
922	while (src < items) {
923		if (ki[src].ki_d.level) {
924			src++;
925			continue;
926		}
927		for (nsrc = 1; src + nsrc < items; nsrc++)
928			if (!ki[src + nsrc].ki_d.level)
929				break;
930
931		for (dst = 0; dst < items; dst++) {
932			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
933				continue;
934			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
935				break;
936		}
937
938		if (dst == items) {
939			src += nsrc;
940			continue;
941		}
942
943		for (ndst = 1; dst + ndst < items; ndst++)
944			if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
945				break;
946
947		for (n = src; n < src + nsrc; n++) {
948			ki[n].ki_d.level += ki[dst].ki_d.level + 1;
949			if (maxlvl < ki[n].ki_d.level)
950				maxlvl = ki[n].ki_d.level;
951		}
952
953		while (nsrc) {
954			if (src < dst) {
955				kn = ki[src];
956				memmove(ki + src, ki + src + 1,
957				    (dst - src + ndst - 1) * sizeof *ki);
958				ki[dst + ndst - 1] = kn;
959				nsrc--;
960				dst--;
961				ndst++;
962			} else if (src != dst + ndst) {
963				kn = ki[src];
964				memmove(ki + dst + ndst + 1, ki + dst + ndst,
965				    (src - dst - ndst) * sizeof *ki);
966				ki[dst + ndst] = kn;
967				ndst++;
968				nsrc--;
969				src++;
970			} else {
971				ndst += nsrc;
972				src += nsrc;
973				nsrc = 0;
974			}
975		}
976	}
977
978	/*
979	 * Now populate ki_d.prefix (instead of ki_d.level) with the command
980	 * prefix used to show descendancies.
981	 */
982	path = malloc((maxlvl + 7) / 8);
983	memset(path, '\0', (maxlvl + 7) / 8);
984	for (src = 0; src < items; src++) {
985		if ((lvl = ki[src].ki_d.level) == 0) {
986			ki[src].ki_d.prefix = NULL;
987			continue;
988		}
989		if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
990			errx(1, "malloc failed");
991		for (n = 0; n < lvl - 2; n++) {
992			ki[src].ki_d.prefix[n * 2] =
993			    path[n / 8] & 1 << (n % 8) ? '|' : ' ';
994			ki[src].ki_d.prefix[n * 2 + 1] = ' ';
995		}
996		if (n == lvl - 2) {
997			/* Have I any more siblings? */
998			for (siblings = 0, dst = src + 1; dst < items; dst++) {
999				if (ki[dst].ki_d.level > lvl)
1000					continue;
1001				if (ki[dst].ki_d.level == lvl)
1002					siblings = 1;
1003				break;
1004			}
1005			if (siblings)
1006				path[n / 8] |= 1 << (n % 8);
1007			else
1008				path[n / 8] &= ~(1 << (n % 8));
1009			ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1010			ki[src].ki_d.prefix[n * 2 + 1] = '-';
1011			n++;
1012		}
1013		strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1014	}
1015	free(path);
1016}
1017
1018static void *
1019expand_list(struct listinfo *inf)
1020{
1021	void *newlist;
1022	int newmax;
1023
1024	newmax = (inf->maxcount + 1) << 1;
1025	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1026	if (newlist == NULL) {
1027		free(inf->l.ptr);
1028		errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1029	}
1030	inf->maxcount = newmax;
1031	inf->l.ptr = newlist;
1032
1033	return (newlist);
1034}
1035
1036static void
1037free_list(struct listinfo *inf)
1038{
1039
1040	inf->count = inf->elemsize = inf->maxcount = 0;
1041	if (inf->l.ptr != NULL)
1042		free(inf->l.ptr);
1043	inf->addelem = NULL;
1044	inf->lname = NULL;
1045	inf->l.ptr = NULL;
1046}
1047
1048static void
1049init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1050    const char *lname)
1051{
1052
1053	inf->count = inf->maxcount = 0;
1054	inf->elemsize = elemsize;
1055	inf->addelem = artn;
1056	inf->lname = lname;
1057	inf->l.ptr = NULL;
1058}
1059
1060VARENT *
1061find_varentry(VAR *v)
1062{
1063	struct varent *vent;
1064
1065	STAILQ_FOREACH(vent, &varlist, next_ve) {
1066		if (strcmp(vent->var->name, v->name) == 0)
1067			return vent;
1068	}
1069	return NULL;
1070}
1071
1072static void
1073scanvars(void)
1074{
1075	struct varent *vent;
1076	VAR *v;
1077
1078	STAILQ_FOREACH(vent, &varlist, next_ve) {
1079		v = vent->var;
1080		if (v->flag & DSIZ) {
1081			v->dwidth = v->width;
1082			v->width = 0;
1083		}
1084		if (v->flag & USER)
1085			needuser = 1;
1086		if (v->flag & COMM)
1087			needcomm = 1;
1088	}
1089}
1090
1091static void
1092dynsizevars(KINFO *ki)
1093{
1094	struct varent *vent;
1095	VAR *v;
1096	int i;
1097
1098	STAILQ_FOREACH(vent, &varlist, next_ve) {
1099		v = vent->var;
1100		if (!(v->flag & DSIZ))
1101			continue;
1102		i = (v->sproc)( ki);
1103		if (v->width < i)
1104			v->width = i;
1105		if (v->width > v->dwidth)
1106			v->width = v->dwidth;
1107	}
1108}
1109
1110static void
1111sizevars(void)
1112{
1113	struct varent *vent;
1114	VAR *v;
1115	int i;
1116
1117	STAILQ_FOREACH(vent, &varlist, next_ve) {
1118		v = vent->var;
1119		i = strlen(vent->header);
1120		if (v->width < i)
1121			v->width = i;
1122		totwidth += v->width + 1;	/* +1 for space */
1123	}
1124	totwidth--;
1125}
1126
1127static const char *
1128fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
1129    char *comm, int maxlen)
1130{
1131	const char *s;
1132
1133	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
1134	return (s);
1135}
1136
1137#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_flag & P_INMEM))
1138
1139static void
1140saveuser(KINFO *ki)
1141{
1142
1143	if (ki->ki_p->ki_flag & P_INMEM) {
1144		/*
1145		 * The u-area might be swapped out, and we can't get
1146		 * at it because we have a crashdump and no swap.
1147		 * If it's here fill in these fields, otherwise, just
1148		 * leave them 0.
1149		 */
1150		ki->ki_valid = 1;
1151	} else
1152		ki->ki_valid = 0;
1153	/*
1154	 * save arguments if needed
1155	 */
1156	if (needcomm) {
1157		if (ki->ki_p->ki_stat == SZOMB)
1158			ki->ki_args = strdup("<defunct>");
1159		else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
1160			ki->ki_args = strdup(fmt(kvm_getargv, ki,
1161			    ki->ki_p->ki_comm, MAXCOMLEN));
1162		else
1163			asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
1164		if (ki->ki_args == NULL)
1165			errx(1, "malloc failed");
1166	} else {
1167		ki->ki_args = NULL;
1168	}
1169	if (needenv) {
1170		if (UREADOK(ki))
1171			ki->ki_env = strdup(fmt(kvm_getenvv, ki,
1172			    (char *)NULL, 0));
1173		else
1174			ki->ki_env = strdup("()");
1175		if (ki->ki_env == NULL)
1176			errx(1, "malloc failed");
1177	} else {
1178		ki->ki_env = NULL;
1179	}
1180}
1181
1182/* A macro used to improve the readability of pscomp(). */
1183#define	DIFF_RETURN(a, b, field) do {	\
1184	if ((a)->field != (b)->field)	\
1185		return (((a)->field < (b)->field) ? -1 : 1); 	\
1186} while (0)
1187
1188static int
1189pscomp(const void *a, const void *b)
1190{
1191	const KINFO *ka, *kb;
1192
1193	ka = a;
1194	kb = b;
1195	/* SORTCPU and SORTMEM are sorted in descending order. */
1196	if (sortby == SORTCPU)
1197		DIFF_RETURN(kb, ka, ki_pcpu);
1198	if (sortby == SORTMEM)
1199		DIFF_RETURN(kb, ka, ki_memsize);
1200	/*
1201	 * TTY's are sorted in ascending order, except that all NODEV
1202	 * processes come before all processes with a device.
1203	 */
1204	if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1205		if (ka->ki_p->ki_tdev == NODEV)
1206			return (-1);
1207		if (kb->ki_p->ki_tdev == NODEV)
1208			return (1);
1209		DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1210	}
1211
1212	/* PID's and TID's (threads) are sorted in ascending order. */
1213	DIFF_RETURN(ka, kb, ki_p->ki_pid);
1214	DIFF_RETURN(ka, kb, ki_p->ki_tid);
1215	return (0);
1216}
1217#undef DIFF_RETURN
1218
1219/*
1220 * ICK (all for getopt), would rather hide the ugliness
1221 * here than taint the main code.
1222 *
1223 *  ps foo -> ps -foo
1224 *  ps 34 -> ps -p34
1225 *
1226 * The old convention that 't' with no trailing tty arg means the users
1227 * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1228 * feature is available with the option 'T', which takes no argument.
1229 */
1230static char *
1231kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1232{
1233	size_t len;
1234	char *argp, *cp, *newopts, *ns, *optp, *pidp;
1235
1236	/*
1237	 * See if the original value includes any option which takes an
1238	 * argument (and will thus use up the remainder of the string).
1239	 */
1240	argp = NULL;
1241	if (optlist != NULL) {
1242		for (cp = origval; *cp != '\0'; cp++) {
1243			optp = strchr(optlist, *cp);
1244			if ((optp != NULL) && *(optp + 1) == ':') {
1245				argp = cp;
1246				break;
1247			}
1248		}
1249	}
1250	if (argp != NULL && *origval == '-')
1251		return (origval);
1252
1253	/*
1254	 * if last letter is a 't' flag with no argument (in the context
1255	 * of the oldps options -- option string NOT starting with a '-' --
1256	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1257	 *
1258	 * However, if a flag accepting a string argument is found earlier
1259	 * in the option string (including a possible `t' flag), then the
1260	 * remainder of the string must be the argument to that flag; so
1261	 * do not modify that argument.  Note that a trailing `t' would
1262	 * cause argp to be set, if argp was not already set by some
1263	 * earlier option.
1264	 */
1265	len = strlen(origval);
1266	cp = origval + len - 1;
1267	pidp = NULL;
1268	if (*cp == 't' && *origval != '-' && cp == argp) {
1269		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1270			*cp = 'T';
1271	} else if (argp == NULL) {
1272		/*
1273		 * The original value did not include any option which takes
1274		 * an argument (and that would include `p' and `t'), so check
1275		 * the value for trailing number, or comma-separated list of
1276		 * numbers, which we will treat as a pid request.
1277		 */
1278		if (isdigitch(*cp)) {
1279			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1280				--cp;
1281			pidp = cp + 1;
1282		}
1283	}
1284
1285	/*
1286	 * If nothing needs to be added to the string, then return
1287	 * the "original" (although possibly modified) value.
1288	 */
1289	if (*origval == '-' && pidp == NULL)
1290		return (origval);
1291
1292	/*
1293	 * Create a copy of the string to add '-' and/or 'p' to the
1294	 * original value.
1295	 */
1296	if ((newopts = ns = malloc(len + 3)) == NULL)
1297		errx(1, "malloc failed");
1298
1299	if (*origval != '-')
1300		*ns++ = '-';	/* add option flag */
1301
1302	if (pidp == NULL)
1303		strcpy(ns, origval);
1304	else {
1305		/*
1306		 * Copy everything before the pid string, add the `p',
1307		 * and then copy the pid string.
1308		 */
1309		len = pidp - origval;
1310		memcpy(ns, origval, len);
1311		ns += len;
1312		*ns++ = 'p';
1313		strcpy(ns, pidp);
1314	}
1315
1316	return (newopts);
1317}
1318
1319static int
1320check_procfs(void)
1321{
1322	struct statfs mnt;
1323
1324	if (statfs("/proc", &mnt) < 0)
1325		return (0);
1326	if (strcmp(mnt.f_fstypename, "procfs") != 0)
1327		return (0);
1328	return (1);
1329}
1330
1331static void
1332usage(void)
1333{
1334#define	SINGLE_OPTS	"[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1335
1336	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1337	    "usage: ps " SINGLE_OPTS " [-O fmt | -o fmt] [-G gid[,gid...]]",
1338	    "          [-M core] [-N system]",
1339	    "          [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",
1340	    "       ps [-L]");
1341	exit(1);
1342}
1343