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