ps.c revision 225868
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 225868 2011-09-29 06:31:42Z trasz $");
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	 showthreads;		/* will threads be shown? */
103
104struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
105
106static int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
107static kvm_t	*kd;
108static int	 needcomm;	/* -o "command" */
109static int	 needenv;	/* -e */
110static int	 needuser;	/* -o "user" */
111static int	 optfatal;	/* Fatal error parsing some list-option. */
112
113static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
114
115struct listinfo;
116typedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
117
118struct listinfo {
119	int		 count;
120	int		 maxcount;
121	int		 elemsize;
122	addelem_rtn	*addelem;
123	const char	*lname;
124	union {
125		gid_t	*gids;
126		pid_t	*pids;
127		dev_t	*ttys;
128		uid_t	*uids;
129		void	*ptr;
130	} l;
131};
132
133static int	 check_procfs(void);
134static int	 addelem_gid(struct listinfo *, const char *);
135static int	 addelem_pid(struct listinfo *, const char *);
136static int	 addelem_tty(struct listinfo *, const char *);
137static int	 addelem_uid(struct listinfo *, const char *);
138static void	 add_list(struct listinfo *, const char *);
139static void	 descendant_sort(KINFO *, int);
140static void	 format_output(KINFO *);
141static void	*expand_list(struct listinfo *);
142static const char *
143		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
144		    KINFO *, char *, int);
145static void	 free_list(struct listinfo *);
146static void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
147static char	*kludge_oldps_options(const char *, char *, const char *);
148static int	 pscomp(const void *, const void *);
149static void	 saveuser(KINFO *);
150static void	 scanvars(void);
151static void	 sizevars(void);
152static void	 usage(void);
153
154static char dfmt[] = "pid,tt,state,time,command";
155static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
156static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
157			"tt,time,command";
158static char   o1[] = "pid";
159static char   o2[] = "tt,state,time,command";
160static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
161static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
162			"%cpu,%mem,command";
163static char Zfmt[] = "label";
164
165#define	PS_ARGS	"AaCcde" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
166
167int
168main(int argc, char *argv[])
169{
170	struct listinfo gidlist, pgrplist, pidlist;
171	struct listinfo ruidlist, sesslist, ttylist, uidlist;
172	struct kinfo_proc *kp;
173	KINFO *kinfo = NULL, *next_KINFO;
174	KINFO_STR *ks;
175	struct varent *vent;
176	struct winsize ws;
177	const char *nlistf, *memf, *fmtstr, *str;
178	char *cols;
179	int all, ch, elem, flag, _fmt, i, lineno, linelen, left;
180	int descendancy, nentries, nkept, nselectors;
181	int prtheader, wflag, what, xkeep, xkeep_implied;
182	char errbuf[_POSIX2_LINE_MAX];
183
184	(void) setlocale(LC_ALL, "");
185	time(&now);			/* Used by routines in print.c. */
186
187	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
188		termwidth = atoi(cols);
189	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
190	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
191	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
192	     ws.ws_col == 0)
193		termwidth = 79;
194	else
195		termwidth = ws.ws_col - 1;
196
197	/*
198	 * Hide a number of option-processing kludges in a separate routine,
199	 * to support some historical BSD behaviors, such as `ps axu'.
200	 */
201	if (argc > 1)
202		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
203
204	all = descendancy = _fmt = nselectors = optfatal = 0;
205	prtheader = showthreads = wflag = xkeep_implied = 0;
206	xkeep = -1;			/* Neither -x nor -X. */
207	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
208	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
209	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
210	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
211	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
212	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
213	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
214	memf = _PATH_DEVNULL;
215	nlistf = NULL;
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 compatibility 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			nkept++;
591		}
592	}
593
594	sizevars();
595
596	if (nkept == 0) {
597		printheader();
598		exit(1);
599	}
600
601	/*
602	 * sort proc list
603	 */
604	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
605
606	/*
607	 * We want things in descendant order
608	 */
609	if (descendancy)
610		descendant_sort(kinfo, nkept);
611
612
613	/*
614	 * Prepare formatted output.
615	 */
616	for (i = 0; i < nkept; i++)
617		format_output(&kinfo[i]);
618
619	/*
620	 * Print header.
621	 */
622	printheader();
623
624	/*
625	 * Output formatted lines.
626	 */
627	for (i = lineno = 0; i < nkept; i++) {
628		linelen = 0;
629		STAILQ_FOREACH(vent, &varlist, next_ve) {
630	        	if (vent->var->flag & LJUST)
631				fmtstr = "%-*s";
632			else
633				fmtstr = "%*s";
634
635			ks = STAILQ_FIRST(&kinfo[i].ki_ks);
636			STAILQ_REMOVE_HEAD(&kinfo[i].ki_ks, ks_next);
637			/* Truncate rightmost column if neccessary.  */
638			if (STAILQ_NEXT(vent, next_ve) == NULL &&
639			   termwidth != UNLIMITED && ks->ks_str != NULL) {
640				left = termwidth - linelen;
641				if (left > 0 && left < (int)strlen(ks->ks_str))
642					ks->ks_str[left] = '\0';
643			}
644			str = ks->ks_str;
645			if (str == NULL)
646				str = "-";
647			/* No padding for the last column, if it's LJUST. */
648			if (STAILQ_NEXT(vent, next_ve) == NULL &&
649			    vent->var->flag & LJUST)
650				linelen += printf(fmtstr, 0, str);
651			else
652				linelen += printf(fmtstr, vent->var->width, str);
653
654			if (ks->ks_str != NULL) {
655				free(ks->ks_str);
656				ks->ks_str = NULL;
657			}
658			free(ks);
659			ks = NULL;
660
661			if (STAILQ_NEXT(vent, next_ve) != NULL) {
662				(void)putchar(' ');
663				linelen++;
664			}
665		}
666		(void)putchar('\n');
667		if (prtheader && lineno++ == prtheader - 4) {
668			(void)putchar('\n');
669			printheader();
670			lineno = 0;
671		}
672	}
673	free_list(&gidlist);
674	free_list(&pidlist);
675	free_list(&pgrplist);
676	free_list(&ruidlist);
677	free_list(&sesslist);
678	free_list(&ttylist);
679	free_list(&uidlist);
680	for (i = 0; i < nkept; i++)
681		free(kinfo[i].ki_d.prefix);
682	free(kinfo);
683
684	exit(eval);
685}
686
687static int
688addelem_gid(struct listinfo *inf, const char *elem)
689{
690	struct group *grp;
691	const char *nameorID;
692	char *endp;
693	u_long bigtemp;
694
695	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
696		if (*elem == '\0')
697			warnx("Invalid (zero-length) %s name", inf->lname);
698		else
699			warnx("%s name too long: %s", inf->lname, elem);
700		optfatal = 1;
701		return (0);		/* Do not add this value. */
702	}
703
704	/*
705	 * SUSv3 states that `ps -G grouplist' should match "real-group
706	 * ID numbers", and does not mention group-names.  I do want to
707	 * also support group-names, so this tries for a group-id first,
708	 * and only tries for a name if that doesn't work.  This is the
709	 * opposite order of what is done in addelem_uid(), but in
710	 * practice the order would only matter for group-names which
711	 * are all-numeric.
712	 */
713	grp = NULL;
714	nameorID = "named";
715	errno = 0;
716	bigtemp = strtoul(elem, &endp, 10);
717	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
718		nameorID = "name or ID matches";
719		grp = getgrgid((gid_t)bigtemp);
720	}
721	if (grp == NULL)
722		grp = getgrnam(elem);
723	if (grp == NULL) {
724		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
725		optfatal = 1;
726		return (0);
727	}
728	if (inf->count >= inf->maxcount)
729		expand_list(inf);
730	inf->l.gids[(inf->count)++] = grp->gr_gid;
731	return (1);
732}
733
734#define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h. */
735static int
736addelem_pid(struct listinfo *inf, const char *elem)
737{
738	char *endp;
739	long tempid;
740
741	if (*elem == '\0') {
742		warnx("Invalid (zero-length) process id");
743		optfatal = 1;
744		return (0);		/* Do not add this value. */
745	}
746
747	errno = 0;
748	tempid = strtol(elem, &endp, 10);
749	if (*endp != '\0' || tempid < 0 || elem == endp) {
750		warnx("Invalid %s: %s", inf->lname, elem);
751		errno = ERANGE;
752	} else if (errno != 0 || tempid > BSD_PID_MAX) {
753		warnx("%s too large: %s", inf->lname, elem);
754		errno = ERANGE;
755	}
756	if (errno == ERANGE) {
757		optfatal = 1;
758		return (0);
759	}
760	if (inf->count >= inf->maxcount)
761		expand_list(inf);
762	inf->l.pids[(inf->count)++] = tempid;
763	return (1);
764}
765#undef	BSD_PID_MAX
766
767/*-
768 * The user can specify a device via one of three formats:
769 *     1) fully qualified, e.g.:     /dev/ttyp0 /dev/console	/dev/pts/0
770 *     2) missing "/dev", e.g.:      ttyp0      console		pts/0
771 *     3) two-letters, e.g.:         p0         co		0
772 *        (matching letters that would be seen in the "TT" column)
773 */
774static int
775addelem_tty(struct listinfo *inf, const char *elem)
776{
777	const char *ttypath;
778	struct stat sb;
779	char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
780
781	ttypath = NULL;
782	pathbuf2[0] = '\0';
783	pathbuf3[0] = '\0';
784	switch (*elem) {
785	case '/':
786		ttypath = elem;
787		break;
788	case 'c':
789		if (strcmp(elem, "co") == 0) {
790			ttypath = _PATH_CONSOLE;
791			break;
792		}
793		/* FALLTHROUGH */
794	default:
795		strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
796		strlcat(pathbuf, elem, sizeof(pathbuf));
797		ttypath = pathbuf;
798		if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
799			break;
800		if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
801			break;
802		if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
803			break;
804		/* Check to see if /dev/tty${elem} exists */
805		strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
806		strlcat(pathbuf2, elem, sizeof(pathbuf2));
807		if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
808			/* No need to repeat stat() && S_ISCHR() checks */
809			ttypath = NULL;
810			break;
811		}
812		/* Check to see if /dev/pts/${elem} exists */
813		strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
814		strlcat(pathbuf3, elem, sizeof(pathbuf3));
815		if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
816			/* No need to repeat stat() && S_ISCHR() checks */
817			ttypath = NULL;
818			break;
819		}
820		break;
821	}
822	if (ttypath) {
823		if (stat(ttypath, &sb) == -1) {
824			if (pathbuf3[0] != '\0')
825				warn("%s, %s, and %s", pathbuf3, pathbuf2,
826				    ttypath);
827			else
828				warn("%s", ttypath);
829			optfatal = 1;
830			return (0);
831		}
832		if (!S_ISCHR(sb.st_mode)) {
833			if (pathbuf3[0] != '\0')
834				warnx("%s, %s, and %s: Not a terminal",
835				    pathbuf3, pathbuf2, ttypath);
836			else
837				warnx("%s: Not a terminal", ttypath);
838			optfatal = 1;
839			return (0);
840		}
841	}
842	if (inf->count >= inf->maxcount)
843		expand_list(inf);
844	inf->l.ttys[(inf->count)++] = sb.st_rdev;
845	return (1);
846}
847
848static int
849addelem_uid(struct listinfo *inf, const char *elem)
850{
851	struct passwd *pwd;
852	char *endp;
853	u_long bigtemp;
854
855	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
856		if (*elem == '\0')
857			warnx("Invalid (zero-length) %s name", inf->lname);
858		else
859			warnx("%s name too long: %s", inf->lname, elem);
860		optfatal = 1;
861		return (0);		/* Do not add this value. */
862	}
863
864	pwd = getpwnam(elem);
865	if (pwd == NULL) {
866		errno = 0;
867		bigtemp = strtoul(elem, &endp, 10);
868		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
869			warnx("No %s named '%s'", inf->lname, elem);
870		else {
871			/* The string is all digits, so it might be a userID. */
872			pwd = getpwuid((uid_t)bigtemp);
873			if (pwd == NULL)
874				warnx("No %s name or ID matches '%s'",
875				    inf->lname, elem);
876		}
877	}
878	if (pwd == NULL) {
879		/*
880		 * These used to be treated as minor warnings (and the
881		 * option was simply ignored), but now they are fatal
882		 * errors (and the command will be aborted).
883		 */
884		optfatal = 1;
885		return (0);
886	}
887	if (inf->count >= inf->maxcount)
888		expand_list(inf);
889	inf->l.uids[(inf->count)++] = pwd->pw_uid;
890	return (1);
891}
892
893static void
894add_list(struct listinfo *inf, const char *argp)
895{
896	const char *savep;
897	char *cp, *endp;
898	int toolong;
899	char elemcopy[PATH_MAX];
900
901	if (*argp == 0)
902		inf->addelem(inf, elemcopy);
903	while (*argp != '\0') {
904		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
905			argp++;
906		savep = argp;
907		toolong = 0;
908		cp = elemcopy;
909		if (strchr(T_SEP, *argp) == NULL) {
910			endp = elemcopy + sizeof(elemcopy) - 1;
911			while (*argp != '\0' && cp <= endp &&
912			    strchr(W_SEP T_SEP, *argp) == NULL)
913				*cp++ = *argp++;
914			if (cp > endp)
915				toolong = 1;
916		}
917		if (!toolong) {
918			*cp = '\0';
919			/*
920			 * Add this single element to the given list.
921			 */
922			inf->addelem(inf, elemcopy);
923		} else {
924			/*
925			 * The string is too long to copy.  Find the end
926			 * of the string to print out the warning message.
927			 */
928			while (*argp != '\0' && strchr(W_SEP T_SEP,
929			    *argp) == NULL)
930				argp++;
931			warnx("Value too long: %.*s", (int)(argp - savep),
932			    savep);
933			optfatal = 1;
934		}
935		/*
936		 * Skip over any number of trailing whitespace characters,
937		 * but only one (at most) trailing element-terminating
938		 * character.
939		 */
940		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
941			argp++;
942		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
943			argp++;
944			/* Catch case where string ended with a comma. */
945			if (*argp == '\0')
946				inf->addelem(inf, argp);
947		}
948	}
949}
950
951static void
952descendant_sort(KINFO *ki, int items)
953{
954	int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
955	unsigned char *path;
956	KINFO kn;
957
958	/*
959	 * First, sort the entries by descendancy, tracking the descendancy
960	 * depth in the ki_d.level field.
961	 */
962	src = 0;
963	maxlvl = 0;
964	while (src < items) {
965		if (ki[src].ki_d.level) {
966			src++;
967			continue;
968		}
969		for (nsrc = 1; src + nsrc < items; nsrc++)
970			if (!ki[src + nsrc].ki_d.level)
971				break;
972
973		for (dst = 0; dst < items; dst++) {
974			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
975				continue;
976			if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
977				break;
978		}
979
980		if (dst == items) {
981			src += nsrc;
982			continue;
983		}
984
985		for (ndst = 1; dst + ndst < items; ndst++)
986			if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
987				break;
988
989		for (n = src; n < src + nsrc; n++) {
990			ki[n].ki_d.level += ki[dst].ki_d.level + 1;
991			if (maxlvl < ki[n].ki_d.level)
992				maxlvl = ki[n].ki_d.level;
993		}
994
995		while (nsrc) {
996			if (src < dst) {
997				kn = ki[src];
998				memmove(ki + src, ki + src + 1,
999				    (dst - src + ndst - 1) * sizeof *ki);
1000				ki[dst + ndst - 1] = kn;
1001				nsrc--;
1002				dst--;
1003				ndst++;
1004			} else if (src != dst + ndst) {
1005				kn = ki[src];
1006				memmove(ki + dst + ndst + 1, ki + dst + ndst,
1007				    (src - dst - ndst) * sizeof *ki);
1008				ki[dst + ndst] = kn;
1009				ndst++;
1010				nsrc--;
1011				src++;
1012			} else {
1013				ndst += nsrc;
1014				src += nsrc;
1015				nsrc = 0;
1016			}
1017		}
1018	}
1019
1020	/*
1021	 * Now populate ki_d.prefix (instead of ki_d.level) with the command
1022	 * prefix used to show descendancies.
1023	 */
1024	path = malloc((maxlvl + 7) / 8);
1025	memset(path, '\0', (maxlvl + 7) / 8);
1026	for (src = 0; src < items; src++) {
1027		if ((lvl = ki[src].ki_d.level) == 0) {
1028			ki[src].ki_d.prefix = NULL;
1029			continue;
1030		}
1031		if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
1032			errx(1, "malloc failed");
1033		for (n = 0; n < lvl - 2; n++) {
1034			ki[src].ki_d.prefix[n * 2] =
1035			    path[n / 8] & 1 << (n % 8) ? '|' : ' ';
1036			ki[src].ki_d.prefix[n * 2 + 1] = ' ';
1037		}
1038		if (n == lvl - 2) {
1039			/* Have I any more siblings? */
1040			for (siblings = 0, dst = src + 1; dst < items; dst++) {
1041				if (ki[dst].ki_d.level > lvl)
1042					continue;
1043				if (ki[dst].ki_d.level == lvl)
1044					siblings = 1;
1045				break;
1046			}
1047			if (siblings)
1048				path[n / 8] |= 1 << (n % 8);
1049			else
1050				path[n / 8] &= ~(1 << (n % 8));
1051			ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1052			ki[src].ki_d.prefix[n * 2 + 1] = '-';
1053			n++;
1054		}
1055		strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1056	}
1057	free(path);
1058}
1059
1060static void *
1061expand_list(struct listinfo *inf)
1062{
1063	void *newlist;
1064	int newmax;
1065
1066	newmax = (inf->maxcount + 1) << 1;
1067	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1068	if (newlist == NULL) {
1069		free(inf->l.ptr);
1070		errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1071	}
1072	inf->maxcount = newmax;
1073	inf->l.ptr = newlist;
1074
1075	return (newlist);
1076}
1077
1078static void
1079free_list(struct listinfo *inf)
1080{
1081
1082	inf->count = inf->elemsize = inf->maxcount = 0;
1083	if (inf->l.ptr != NULL)
1084		free(inf->l.ptr);
1085	inf->addelem = NULL;
1086	inf->lname = NULL;
1087	inf->l.ptr = NULL;
1088}
1089
1090static void
1091init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1092    const char *lname)
1093{
1094
1095	inf->count = inf->maxcount = 0;
1096	inf->elemsize = elemsize;
1097	inf->addelem = artn;
1098	inf->lname = lname;
1099	inf->l.ptr = NULL;
1100}
1101
1102VARENT *
1103find_varentry(VAR *v)
1104{
1105	struct varent *vent;
1106
1107	STAILQ_FOREACH(vent, &varlist, next_ve) {
1108		if (strcmp(vent->var->name, v->name) == 0)
1109			return vent;
1110	}
1111	return NULL;
1112}
1113
1114static void
1115scanvars(void)
1116{
1117	struct varent *vent;
1118	VAR *v;
1119
1120	STAILQ_FOREACH(vent, &varlist, next_ve) {
1121		v = vent->var;
1122		if (v->flag & USER)
1123			needuser = 1;
1124		if (v->flag & COMM)
1125			needcomm = 1;
1126	}
1127}
1128
1129static void
1130format_output(KINFO *ki)
1131{
1132	struct varent *vent;
1133	VAR *v;
1134	KINFO_STR *ks;
1135	char *str;
1136	int len;
1137
1138	STAILQ_INIT(&ki->ki_ks);
1139	STAILQ_FOREACH(vent, &varlist, next_ve) {
1140		v = vent->var;
1141		str = (v->oproc)(ki, vent);
1142		ks = malloc(sizeof(*ks));
1143		if (ks == NULL)
1144			errx(1, "malloc failed");
1145		ks->ks_str = str;
1146		STAILQ_INSERT_TAIL(&ki->ki_ks, ks, ks_next);
1147		if (str != NULL) {
1148			len = strlen(str);
1149		} else
1150			len = 1; /* "-" */
1151		if (v->width < len)
1152			v->width = len;
1153	}
1154}
1155
1156static void
1157sizevars(void)
1158{
1159	struct varent *vent;
1160	VAR *v;
1161	int i;
1162
1163	STAILQ_FOREACH(vent, &varlist, next_ve) {
1164		v = vent->var;
1165		i = strlen(vent->header);
1166		if (v->width < i)
1167			v->width = i;
1168	}
1169}
1170
1171static const char *
1172fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
1173    char *comm, int maxlen)
1174{
1175	const char *s;
1176
1177	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
1178	return (s);
1179}
1180
1181#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_flag & P_INMEM))
1182
1183static void
1184saveuser(KINFO *ki)
1185{
1186
1187	if (ki->ki_p->ki_flag & P_INMEM) {
1188		/*
1189		 * The u-area might be swapped out, and we can't get
1190		 * at it because we have a crashdump and no swap.
1191		 * If it's here fill in these fields, otherwise, just
1192		 * leave them 0.
1193		 */
1194		ki->ki_valid = 1;
1195	} else
1196		ki->ki_valid = 0;
1197	/*
1198	 * save arguments if needed
1199	 */
1200	if (needcomm) {
1201		if (ki->ki_p->ki_stat == SZOMB)
1202			ki->ki_args = strdup("<defunct>");
1203		else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
1204			ki->ki_args = strdup(fmt(kvm_getargv, ki,
1205			    ki->ki_p->ki_comm, MAXCOMLEN));
1206		else
1207			asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
1208		if (ki->ki_args == NULL)
1209			errx(1, "malloc failed");
1210	} else {
1211		ki->ki_args = NULL;
1212	}
1213	if (needenv) {
1214		if (UREADOK(ki))
1215			ki->ki_env = strdup(fmt(kvm_getenvv, ki,
1216			    (char *)NULL, 0));
1217		else
1218			ki->ki_env = strdup("()");
1219		if (ki->ki_env == NULL)
1220			errx(1, "malloc failed");
1221	} else {
1222		ki->ki_env = NULL;
1223	}
1224}
1225
1226/* A macro used to improve the readability of pscomp(). */
1227#define	DIFF_RETURN(a, b, field) do {	\
1228	if ((a)->field != (b)->field)	\
1229		return (((a)->field < (b)->field) ? -1 : 1); 	\
1230} while (0)
1231
1232static int
1233pscomp(const void *a, const void *b)
1234{
1235	const KINFO *ka, *kb;
1236
1237	ka = a;
1238	kb = b;
1239	/* SORTCPU and SORTMEM are sorted in descending order. */
1240	if (sortby == SORTCPU)
1241		DIFF_RETURN(kb, ka, ki_pcpu);
1242	if (sortby == SORTMEM)
1243		DIFF_RETURN(kb, ka, ki_memsize);
1244	/*
1245	 * TTY's are sorted in ascending order, except that all NODEV
1246	 * processes come before all processes with a device.
1247	 */
1248	if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1249		if (ka->ki_p->ki_tdev == NODEV)
1250			return (-1);
1251		if (kb->ki_p->ki_tdev == NODEV)
1252			return (1);
1253		DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1254	}
1255
1256	/* PID's and TID's (threads) are sorted in ascending order. */
1257	DIFF_RETURN(ka, kb, ki_p->ki_pid);
1258	DIFF_RETURN(ka, kb, ki_p->ki_tid);
1259	return (0);
1260}
1261#undef DIFF_RETURN
1262
1263/*
1264 * ICK (all for getopt), would rather hide the ugliness
1265 * here than taint the main code.
1266 *
1267 *  ps foo -> ps -foo
1268 *  ps 34 -> ps -p34
1269 *
1270 * The old convention that 't' with no trailing tty arg means the users
1271 * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1272 * feature is available with the option 'T', which takes no argument.
1273 */
1274static char *
1275kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1276{
1277	size_t len;
1278	char *argp, *cp, *newopts, *ns, *optp, *pidp;
1279
1280	/*
1281	 * See if the original value includes any option which takes an
1282	 * argument (and will thus use up the remainder of the string).
1283	 */
1284	argp = NULL;
1285	if (optlist != NULL) {
1286		for (cp = origval; *cp != '\0'; cp++) {
1287			optp = strchr(optlist, *cp);
1288			if ((optp != NULL) && *(optp + 1) == ':') {
1289				argp = cp;
1290				break;
1291			}
1292		}
1293	}
1294	if (argp != NULL && *origval == '-')
1295		return (origval);
1296
1297	/*
1298	 * if last letter is a 't' flag with no argument (in the context
1299	 * of the oldps options -- option string NOT starting with a '-' --
1300	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1301	 *
1302	 * However, if a flag accepting a string argument is found earlier
1303	 * in the option string (including a possible `t' flag), then the
1304	 * remainder of the string must be the argument to that flag; so
1305	 * do not modify that argument.  Note that a trailing `t' would
1306	 * cause argp to be set, if argp was not already set by some
1307	 * earlier option.
1308	 */
1309	len = strlen(origval);
1310	cp = origval + len - 1;
1311	pidp = NULL;
1312	if (*cp == 't' && *origval != '-' && cp == argp) {
1313		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1314			*cp = 'T';
1315	} else if (argp == NULL) {
1316		/*
1317		 * The original value did not include any option which takes
1318		 * an argument (and that would include `p' and `t'), so check
1319		 * the value for trailing number, or comma-separated list of
1320		 * numbers, which we will treat as a pid request.
1321		 */
1322		if (isdigitch(*cp)) {
1323			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1324				--cp;
1325			pidp = cp + 1;
1326		}
1327	}
1328
1329	/*
1330	 * If nothing needs to be added to the string, then return
1331	 * the "original" (although possibly modified) value.
1332	 */
1333	if (*origval == '-' && pidp == NULL)
1334		return (origval);
1335
1336	/*
1337	 * Create a copy of the string to add '-' and/or 'p' to the
1338	 * original value.
1339	 */
1340	if ((newopts = ns = malloc(len + 3)) == NULL)
1341		errx(1, "malloc failed");
1342
1343	if (*origval != '-')
1344		*ns++ = '-';	/* add option flag */
1345
1346	if (pidp == NULL)
1347		strcpy(ns, origval);
1348	else {
1349		/*
1350		 * Copy everything before the pid string, add the `p',
1351		 * and then copy the pid string.
1352		 */
1353		len = pidp - origval;
1354		memcpy(ns, origval, len);
1355		ns += len;
1356		*ns++ = 'p';
1357		strcpy(ns, pidp);
1358	}
1359
1360	return (newopts);
1361}
1362
1363static int
1364check_procfs(void)
1365{
1366	struct statfs mnt;
1367
1368	if (statfs("/proc", &mnt) < 0)
1369		return (0);
1370	if (strcmp(mnt.f_fstypename, "procfs") != 0)
1371		return (0);
1372	return (1);
1373}
1374
1375static void
1376usage(void)
1377{
1378#define	SINGLE_OPTS	"[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1379
1380	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1381	    "usage: ps " SINGLE_OPTS " [-O fmt | -o fmt] [-G gid[,gid...]]",
1382	    "          [-M core] [-N system]",
1383	    "          [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",
1384	    "       ps [-L]");
1385	exit(1);
1386}
1387