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