ps.c revision 110391
11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1990, 1993, 1994
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * Redistribution and use in source and binary forms, with or without
61556Srgrimes * modification, are permitted provided that the following conditions
71556Srgrimes * are met:
81556Srgrimes * 1. Redistributions of source code must retain the above copyright
91556Srgrimes *    notice, this list of conditions and the following disclaimer.
101556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111556Srgrimes *    notice, this list of conditions and the following disclaimer in the
121556Srgrimes *    documentation and/or other materials provided with the distribution.
131556Srgrimes * 3. All advertising materials mentioning features or use of this software
141556Srgrimes *    must display the following acknowledgement:
151556Srgrimes *	This product includes software developed by the University of
161556Srgrimes *	California, Berkeley and its contributors.
171556Srgrimes * 4. Neither the name of the University nor the names of its contributors
181556Srgrimes *    may be used to endorse or promote products derived from this software
191556Srgrimes *    without specific prior written permission.
201556Srgrimes *
211556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
221556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
231556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
241556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
251556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
261556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
271556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
281556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
291556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
301556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311556Srgrimes * SUCH DAMAGE.
321556Srgrimes */
331556Srgrimes
341556Srgrimes#ifndef lint
3590143Smarkmstatic const char copyright[] =
361556Srgrimes"@(#) Copyright (c) 1990, 1993, 1994\n\
371556Srgrimes	The Regents of the University of California.  All rights reserved.\n";
381556Srgrimes#endif /* not lint */
391556Srgrimes
4090143Smarkm#if 0
411556Srgrimes#ifndef lint
4236049Scharnierstatic char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
4390143Smarkm#endif /* not lint */
4436049Scharnier#endif
45110391Scharnier
4699110Sobrien#include <sys/cdefs.h>
4799110Sobrien__FBSDID("$FreeBSD: head/bin/ps/ps.c 110391 2003-02-05 13:18:17Z charnier $");
481556Srgrimes
491556Srgrimes#include <sys/param.h>
503296Sdg#include <sys/user.h>
511556Srgrimes#include <sys/stat.h>
521556Srgrimes#include <sys/ioctl.h>
531556Srgrimes#include <sys/sysctl.h>
541556Srgrimes
551556Srgrimes#include <ctype.h>
561556Srgrimes#include <err.h>
571556Srgrimes#include <fcntl.h>
581556Srgrimes#include <kvm.h>
5913514Smpp#include <limits.h>
6073367Sache#include <locale.h>
611556Srgrimes#include <paths.h>
6290143Smarkm#include <pwd.h>
631556Srgrimes#include <stdio.h>
641556Srgrimes#include <stdlib.h>
651556Srgrimes#include <string.h>
661556Srgrimes#include <unistd.h>
671556Srgrimes
681556Srgrimes#include "ps.h"
691556Srgrimes
7066377Sbrian#define SEP ", \t"		/* username separators */
7166377Sbrian
7290143Smarkmstatic KINFO *kinfo;
7390143Smarkmstruct varent *vhead;
741556Srgrimes
751556Srgrimesint	eval;			/* exit value */
7619068Speterint	cflag;			/* -c */
771556Srgrimesint	rawcpu;			/* -C */
781556Srgrimesint	sumrusage;		/* -S */
791556Srgrimesint	termwidth;		/* width of screen (0 == infinity) */
801556Srgrimesint	totwidth;		/* calculated width of requested variables */
811556Srgrimes
8297966Sjmalletttime_t	now;			/* current time(3) value */
8397966Sjmallett
841556Srgrimesstatic int needuser, needcomm, needenv;
8531552Sdyson#if defined(LAZY_PS)
8631552Sdysonstatic int forceuread=0;
8731552Sdyson#else
8831552Sdysonstatic int forceuread=1;
8931552Sdyson#endif
901556Srgrimes
9190143Smarkmstatic enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
921556Srgrimes
9390143Smarkmstatic const	 char *fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
9490110Simp		    KINFO *, char *, int);
9590110Simpstatic char	*kludge_oldps_options(char *);
9690110Simpstatic int	 pscomp(const void *, const void *);
9790110Simpstatic void	 saveuser(KINFO *);
9890110Simpstatic void	 scanvars(void);
9990110Simpstatic void	 dynsizevars(KINFO *);
10090110Simpstatic void	 sizevars(void);
10190110Simpstatic void	 usage(void);
10266377Sbrianstatic uid_t	*getuids(const char *, int *);
1031556Srgrimes
10497875Sjmallettstatic char dfmt[] = "pid,tt,state,time,command";
10597875Sjmallettstatic char jfmt[] = "user,pid,ppid,pgid,jobc,state,tt,time,command";
10697875Sjmallettstatic char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,tt,time,command";
10790143Smarkmstatic char   o1[] = "pid";
10897875Sjmallettstatic char   o2[] = "tt,state,time,command";
10997875Sjmallettstatic char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
11097875Sjmallettstatic char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,%cpu,%mem,command";
111105831Srwatsonstatic char Zfmt[] = "label";
1121556Srgrimes
11390143Smarkmstatic kvm_t *kd;
1141556Srgrimes
11598494Ssobomax#if defined(LAZY_PS)
11698494Ssobomax#define PS_ARGS	"aCcefghjLlM:mN:O:o:p:rSTt:U:uvwxZ"
11798494Ssobomax#else
11898494Ssobomax#define PS_ARGS	"aCceghjLlM:mN:O:o:p:rSTt:U:uvwxZ"
11998494Ssobomax#endif
12098494Ssobomax
1211556Srgrimesint
12290110Simpmain(int argc, char *argv[])
1231556Srgrimes{
1241556Srgrimes	struct kinfo_proc *kp;
1251556Srgrimes	struct varent *vent;
1261556Srgrimes	struct winsize ws;
1271556Srgrimes	dev_t ttydev;
1281556Srgrimes	pid_t pid;
12966377Sbrian	uid_t *uids;
13098494Ssobomax	int all, ch, flag, i, _fmt, lineno, nentries, nocludge, dropgid;
13166377Sbrian	int prtheader, wflag, what, xflg, uid, nuids;
13297804Stjr	char *cols;
13390143Smarkm	char errbuf[_POSIX2_LINE_MAX];
13498494Ssobomax	const char *cp, *nlistf, *memf;
1351556Srgrimes
13611809Sache	(void) setlocale(LC_ALL, "");
13797966Sjmallett	/* Set the time to what it is right now. */
13897966Sjmallett	time(&now);
13911809Sache
14097804Stjr	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
14197804Stjr		termwidth = atoi(cols);
14297804Stjr	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1431556Srgrimes	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1441556Srgrimes	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
1451556Srgrimes	     ws.ws_col == 0)
1461556Srgrimes		termwidth = 79;
1471556Srgrimes	else
1481556Srgrimes		termwidth = ws.ws_col - 1;
1491556Srgrimes
15098494Ssobomax	/*
15198494Ssobomax	 * Don't apply a kludge if the first argument is an option taking an
15298494Ssobomax	 * argument
15398494Ssobomax	 */
15498494Ssobomax	if (argc > 1) {
15598494Ssobomax		nocludge = 0;
15698494Ssobomax		if (argv[1][0] == '-') {
15798494Ssobomax			for (cp = PS_ARGS; *cp != '\0'; cp++) {
15898494Ssobomax				if (*cp != ':')
15998494Ssobomax					continue;
16098494Ssobomax				if (*(cp - 1) == argv[1][1]) {
16198494Ssobomax					nocludge = 1;
16298494Ssobomax					break;
16398494Ssobomax				}
16498494Ssobomax			}
16598494Ssobomax		}
16698494Ssobomax		if (nocludge == 0)
16798494Ssobomax			argv[1] = kludge_oldps_options(argv[1]);
16898494Ssobomax	}
1691556Srgrimes
17090143Smarkm	all = _fmt = prtheader = wflag = xflg = 0;
1711556Srgrimes	pid = -1;
17266377Sbrian	nuids = 0;
17366377Sbrian	uids = NULL;
1741556Srgrimes	ttydev = NODEV;
17537317Sphk	dropgid = 0;
17689909Sru	memf = nlistf = _PATH_DEVNULL;
17798494Ssobomax	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
1781556Srgrimes		switch((char)ch) {
1791556Srgrimes		case 'a':
1801556Srgrimes			all = 1;
1811556Srgrimes			break;
18219068Speter		case 'C':
18319068Speter			rawcpu = 1;
18419068Speter			break;
18519068Speter		case 'c':
18619068Speter			cflag = 1;
18719068Speter			break;
1881556Srgrimes		case 'e':			/* XXX set ufmt */
1891556Srgrimes			needenv = 1;
1901556Srgrimes			break;
1911556Srgrimes		case 'g':
1921556Srgrimes			break;			/* no-op */
1931556Srgrimes		case 'h':
1941556Srgrimes			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
1951556Srgrimes			break;
1961556Srgrimes		case 'j':
197109502Sjmallett			parsefmt(jfmt, 0);
19890143Smarkm			_fmt = 1;
1991556Srgrimes			jfmt[0] = '\0';
2001556Srgrimes			break;
2011556Srgrimes		case 'L':
2021556Srgrimes			showkey();
2031556Srgrimes			exit(0);
2041556Srgrimes		case 'l':
205109502Sjmallett			parsefmt(lfmt, 0);
20690143Smarkm			_fmt = 1;
2071556Srgrimes			lfmt[0] = '\0';
2081556Srgrimes			break;
2091556Srgrimes		case 'M':
2101556Srgrimes			memf = optarg;
21137317Sphk			dropgid = 1;
2121556Srgrimes			break;
2131556Srgrimes		case 'm':
2141556Srgrimes			sortby = SORTMEM;
2151556Srgrimes			break;
2161556Srgrimes		case 'N':
2171556Srgrimes			nlistf = optarg;
21837317Sphk			dropgid = 1;
2191556Srgrimes			break;
2201556Srgrimes		case 'O':
221109502Sjmallett			parsefmt(o1, 1);
222109502Sjmallett			parsefmt(optarg, 1);
223109502Sjmallett			parsefmt(o2, 1);
2241556Srgrimes			o1[0] = o2[0] = '\0';
22590143Smarkm			_fmt = 1;
2261556Srgrimes			break;
2271556Srgrimes		case 'o':
228109502Sjmallett			parsefmt(optarg, 1);
22990143Smarkm			_fmt = 1;
2301556Srgrimes			break;
23131552Sdyson#if defined(LAZY_PS)
23231552Sdyson		case 'f':
23331552Sdyson			if (getuid() == 0 || getgid() == 0)
23431552Sdyson			    forceuread = 1;
23531552Sdyson			break;
23631552Sdyson#endif
2371556Srgrimes		case 'p':
2381556Srgrimes			pid = atol(optarg);
2391556Srgrimes			xflg = 1;
2401556Srgrimes			break;
2411556Srgrimes		case 'r':
2421556Srgrimes			sortby = SORTCPU;
2431556Srgrimes			break;
2441556Srgrimes		case 'S':
2451556Srgrimes			sumrusage = 1;
2461556Srgrimes			break;
2471556Srgrimes		case 'T':
2481556Srgrimes			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
2491556Srgrimes				errx(1, "stdin: not a terminal");
2501556Srgrimes			/* FALLTHROUGH */
2511556Srgrimes		case 't': {
2521556Srgrimes			struct stat sb;
25377459Simp			char *ttypath, pathbuf[PATH_MAX];
2541556Srgrimes
2551556Srgrimes			if (strcmp(optarg, "co") == 0)
25690143Smarkm				ttypath = strdup(_PATH_CONSOLE);
2571556Srgrimes			else if (*optarg != '/')
2581556Srgrimes				(void)snprintf(ttypath = pathbuf,
2591556Srgrimes				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
2601556Srgrimes			else
2611556Srgrimes				ttypath = optarg;
2621556Srgrimes			if (stat(ttypath, &sb) == -1)
2631556Srgrimes				err(1, "%s", ttypath);
2641556Srgrimes			if (!S_ISCHR(sb.st_mode))
2651556Srgrimes				errx(1, "%s: not a terminal", ttypath);
2661556Srgrimes			ttydev = sb.st_rdev;
2671556Srgrimes			break;
2681556Srgrimes		}
26913020Speter		case 'U':
27066377Sbrian			uids = getuids(optarg, &nuids);
27113020Speter			xflg++;		/* XXX: intuitive? */
27213020Speter			break;
2731556Srgrimes		case 'u':
274109502Sjmallett			parsefmt(ufmt, 0);
2751556Srgrimes			sortby = SORTCPU;
27690143Smarkm			_fmt = 1;
2771556Srgrimes			ufmt[0] = '\0';
2781556Srgrimes			break;
2791556Srgrimes		case 'v':
280109502Sjmallett			parsefmt(vfmt, 0);
2811556Srgrimes			sortby = SORTMEM;
28290143Smarkm			_fmt = 1;
2831556Srgrimes			vfmt[0] = '\0';
2841556Srgrimes			break;
2851556Srgrimes		case 'w':
2861556Srgrimes			if (wflag)
2871556Srgrimes				termwidth = UNLIMITED;
2881556Srgrimes			else if (termwidth < 131)
2891556Srgrimes				termwidth = 131;
2901556Srgrimes			wflag++;
2911556Srgrimes			break;
2921556Srgrimes		case 'x':
2931556Srgrimes			xflg = 1;
2941556Srgrimes			break;
29586922Sgreen		case 'Z':
296109502Sjmallett			parsefmt(Zfmt, 0);
29786922Sgreen			Zfmt[0] = '\0';
29886922Sgreen			break;
2991556Srgrimes		case '?':
3001556Srgrimes		default:
3011556Srgrimes			usage();
3021556Srgrimes		}
3031556Srgrimes	argc -= optind;
3041556Srgrimes	argv += optind;
3051556Srgrimes
3061556Srgrimes#define	BACKWARD_COMPATIBILITY
3071556Srgrimes#ifdef	BACKWARD_COMPATIBILITY
3081556Srgrimes	if (*argv) {
3091556Srgrimes		nlistf = *argv;
3101556Srgrimes		if (*++argv) {
3111556Srgrimes			memf = *argv;
3121556Srgrimes		}
3131556Srgrimes	}
3141556Srgrimes#endif
3151556Srgrimes	/*
3161556Srgrimes	 * Discard setgid privileges if not the running kernel so that bad
3171556Srgrimes	 * guys can't print interesting stuff from kernel memory.
3181556Srgrimes	 */
31937317Sphk	if (dropgid) {
3201556Srgrimes		setgid(getgid());
32137317Sphk		setuid(getuid());
32237317Sphk	}
3231556Srgrimes
32489909Sru	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
3251556Srgrimes	if (kd == 0)
3261556Srgrimes		errx(1, "%s", errbuf);
3271556Srgrimes
32890143Smarkm	if (!_fmt)
329109502Sjmallett		parsefmt(dfmt, 0);
3301556Srgrimes
33113020Speter	/* XXX - should be cleaner */
33266377Sbrian	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
33366377Sbrian		if ((uids = malloc(sizeof (*uids))) == NULL)
33497877Sjmallett			errx(1, "malloc failed");
33566377Sbrian		nuids = 1;
33666377Sbrian		*uids = getuid();
33766377Sbrian	}
3381556Srgrimes
3391556Srgrimes	/*
3401556Srgrimes	 * scan requested variables, noting what structures are needed,
34153170Skris	 * and adjusting header widths as appropriate.
3421556Srgrimes	 */
3431556Srgrimes	scanvars();
3441556Srgrimes	/*
3451556Srgrimes	 * get proc list
3461556Srgrimes	 */
34766377Sbrian	if (nuids == 1) {
3481556Srgrimes		what = KERN_PROC_UID;
34966377Sbrian		flag = *uids;
3501556Srgrimes	} else if (ttydev != NODEV) {
3511556Srgrimes		what = KERN_PROC_TTY;
3521556Srgrimes		flag = ttydev;
3531556Srgrimes	} else if (pid != -1) {
3541556Srgrimes		what = KERN_PROC_PID;
3551556Srgrimes		flag = pid;
3561556Srgrimes	} else {
3571556Srgrimes		what = KERN_PROC_ALL;
3581556Srgrimes		flag = 0;
3591556Srgrimes	}
3601556Srgrimes	/*
3611556Srgrimes	 * select procs
3621556Srgrimes	 */
36382267Speter	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0 || nentries < 0)
3641556Srgrimes		errx(1, "%s", kvm_geterr(kd));
3651556Srgrimes	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
36697877Sjmallett		errx(1, "malloc failed");
3671556Srgrimes	for (i = nentries; --i >= 0; ++kp) {
3681556Srgrimes		kinfo[i].ki_p = kp;
3691556Srgrimes		if (needuser)
3701556Srgrimes			saveuser(&kinfo[i]);
37125271Sjkh		dynsizevars(&kinfo[i]);
3721556Srgrimes	}
37325271Sjkh
37425271Sjkh	sizevars();
37525271Sjkh
3761556Srgrimes	/*
3771556Srgrimes	 * print header
3781556Srgrimes	 */
3791556Srgrimes	printheader();
3801556Srgrimes	if (nentries == 0)
38162803Swill		exit(1);
3821556Srgrimes	/*
3831556Srgrimes	 * sort proc list
3841556Srgrimes	 */
3851556Srgrimes	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
3861556Srgrimes	/*
3871556Srgrimes	 * for each proc, call each variable output function.
3881556Srgrimes	 */
3891556Srgrimes	for (i = lineno = 0; i < nentries; i++) {
39069896Smckusick		if (xflg == 0 && ((&kinfo[i])->ki_p->ki_tdev == NODEV ||
39169896Smckusick		    ((&kinfo[i])->ki_p->ki_flag & P_CONTROLT ) == 0))
3921556Srgrimes			continue;
39366377Sbrian		if (nuids > 1) {
39466377Sbrian			for (uid = 0; uid < nuids; uid++)
39569896Smckusick				if ((&kinfo[i])->ki_p->ki_uid == uids[uid])
39666377Sbrian					break;
39766377Sbrian			if (uid == nuids)
39866377Sbrian				continue;
39966377Sbrian		}
4001556Srgrimes		for (vent = vhead; vent; vent = vent->next) {
4011556Srgrimes			(vent->var->oproc)(&kinfo[i], vent);
4021556Srgrimes			if (vent->next != NULL)
4031556Srgrimes				(void)putchar(' ');
4041556Srgrimes		}
4051556Srgrimes		(void)putchar('\n');
4061556Srgrimes		if (prtheader && lineno++ == prtheader - 4) {
4071556Srgrimes			(void)putchar('\n');
4081556Srgrimes			printheader();
4091556Srgrimes			lineno = 0;
4101556Srgrimes		}
4111556Srgrimes	}
41266377Sbrian	free(uids);
41366377Sbrian
4141556Srgrimes	exit(eval);
4151556Srgrimes}
4161556Srgrimes
41766377Sbrianuid_t *
41866377Sbriangetuids(const char *arg, int *nuids)
41966377Sbrian{
42099580Srobert	char name[MAXLOGNAME];
42166377Sbrian	struct passwd *pwd;
42266377Sbrian	uid_t *uids, *moreuids;
42390143Smarkm	int alloc;
42490143Smarkm	size_t l;
42566377Sbrian
42666377Sbrian
42766377Sbrian	alloc = 0;
42866377Sbrian	*nuids = 0;
42966377Sbrian	uids = NULL;
43066377Sbrian	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
43166377Sbrian		if (l >= sizeof name) {
43290143Smarkm			warnx("%.*s: name too long", (int)l, arg);
43366377Sbrian			continue;
43466377Sbrian		}
43566377Sbrian		strncpy(name, arg, l);
43666377Sbrian		name[l] = '\0';
43766377Sbrian		if ((pwd = getpwnam(name)) == NULL) {
43866377Sbrian			warnx("%s: no such user", name);
43966377Sbrian			continue;
44066377Sbrian		}
44166377Sbrian		if (*nuids >= alloc) {
44266377Sbrian			alloc = (alloc + 1) << 1;
44366377Sbrian			moreuids = realloc(uids, alloc * sizeof (*uids));
44466377Sbrian			if (moreuids == NULL) {
44566377Sbrian				free(uids);
44697877Sjmallett				errx(1, "realloc failed");
44766377Sbrian			}
44866377Sbrian			uids = moreuids;
44966377Sbrian		}
45066377Sbrian		uids[(*nuids)++] = pwd->pw_uid;
45166377Sbrian	}
45266377Sbrian	endpwent();
45366377Sbrian
45466377Sbrian	if (!*nuids)
45566377Sbrian		errx(1, "No users specified");
45666377Sbrian
45766377Sbrian	return uids;
45866377Sbrian}
45966377Sbrian
460109502SjmallettVARENT *
461109502Sjmallettfind_varentry(VAR *v)
462109502Sjmallett{
463109502Sjmallett	struct varent *vent;
464109502Sjmallett
465109502Sjmallett	for (vent = vhead; vent; vent = vent->next) {
466109502Sjmallett		if (strcmp(vent->var->name, v->name) == 0)
467109502Sjmallett			return vent;
468109502Sjmallett	}
469109502Sjmallett	return NULL;
470109502Sjmallett}
471109502Sjmallett
4721556Srgrimesstatic void
47390110Simpscanvars(void)
4741556Srgrimes{
4751556Srgrimes	struct varent *vent;
4761556Srgrimes	VAR *v;
47725271Sjkh
47825271Sjkh	for (vent = vhead; vent; vent = vent->next) {
47925271Sjkh		v = vent->var;
48025271Sjkh		if (v->flag & DSIZ) {
48125271Sjkh			v->dwidth = v->width;
48225271Sjkh			v->width = 0;
48325271Sjkh		}
48425271Sjkh		if (v->flag & USER)
48525271Sjkh			needuser = 1;
48625271Sjkh		if (v->flag & COMM)
48725271Sjkh			needcomm = 1;
48825271Sjkh	}
48925271Sjkh}
49025271Sjkh
49125271Sjkhstatic void
49290110Simpdynsizevars(KINFO *ki)
49325271Sjkh{
49425271Sjkh	struct varent *vent;
49525271Sjkh	VAR *v;
4961556Srgrimes	int i;
4971556Srgrimes
4981556Srgrimes	for (vent = vhead; vent; vent = vent->next) {
4991556Srgrimes		v = vent->var;
50025271Sjkh		if (!(v->flag & DSIZ))
50125271Sjkh			continue;
50225271Sjkh		i = (v->sproc)( ki);
50325271Sjkh		if (v->width < i)
50425271Sjkh			v->width = i;
50525271Sjkh		if (v->width > v->dwidth)
50625271Sjkh			v->width = v->dwidth;
50725271Sjkh	}
50825271Sjkh}
50925271Sjkh
51025271Sjkhstatic void
51190110Simpsizevars(void)
51225271Sjkh{
51325271Sjkh	struct varent *vent;
51425271Sjkh	VAR *v;
51525271Sjkh	int i;
51625271Sjkh
51725271Sjkh	for (vent = vhead; vent; vent = vent->next) {
51825271Sjkh		v = vent->var;
519109504Sjmallett		i = strlen(vent->header);
5201556Srgrimes		if (v->width < i)
5211556Srgrimes			v->width = i;
5221556Srgrimes		totwidth += v->width + 1;	/* +1 for space */
5231556Srgrimes	}
5241556Srgrimes	totwidth--;
5251556Srgrimes}
5261556Srgrimes
52790143Smarkmstatic const char *
52890110Simpfmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
52990110Simp  char *comm, int maxlen)
5301556Srgrimes{
53190143Smarkm	const char *s;
5321556Srgrimes
53390143Smarkm	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
5341556Srgrimes	return (s);
5351556Srgrimes}
5361556Srgrimes
53771578Sjhb#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
53831552Sdyson
5391556Srgrimesstatic void
54090110Simpsaveuser(KINFO *ki)
5411556Srgrimes{
5421556Srgrimes
54371578Sjhb	if (ki->ki_p->ki_sflag & PS_INMEM) {
5441556Srgrimes		/*
5451556Srgrimes		 * The u-area might be swapped out, and we can't get
5461556Srgrimes		 * at it because we have a crashdump and no swap.
5471556Srgrimes		 * If it's here fill in these fields, otherwise, just
5481556Srgrimes		 * leave them 0.
5491556Srgrimes		 */
55069896Smckusick		ki->ki_valid = 1;
5511556Srgrimes	} else
55269896Smckusick		ki->ki_valid = 0;
5531556Srgrimes	/*
5541556Srgrimes	 * save arguments if needed
5551556Srgrimes	 */
55669896Smckusick	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
55790143Smarkm		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
55890143Smarkm		    MAXCOMLEN));
55931552Sdyson	} else if (needcomm) {
56090143Smarkm		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
56153276Speter	} else {
56253276Speter		ki->ki_args = NULL;
56353276Speter	}
56453276Speter	if (needenv && UREADOK(ki)) {
56590143Smarkm		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
56653276Speter	} else if (needenv) {
56753276Speter		ki->ki_env = malloc(3);
56853276Speter		strcpy(ki->ki_env, "()");
56953276Speter	} else {
57053276Speter		ki->ki_env = NULL;
57153276Speter	}
5721556Srgrimes}
5731556Srgrimes
5741556Srgrimesstatic int
57590110Simppscomp(const void *a, const void *b)
5761556Srgrimes{
5771556Srgrimes	int i;
57869896Smckusick#define VSIZE(k) ((k)->ki_p->ki_dsize + (k)->ki_p->ki_ssize + \
57969896Smckusick		  (k)->ki_p->ki_tsize)
5801556Srgrimes
5811556Srgrimes	if (sortby == SORTCPU)
58290143Smarkm		return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
5831556Srgrimes	if (sortby == SORTMEM)
58490143Smarkm		return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
58590143Smarkm	i =  (int)((const KINFO *)a)->ki_p->ki_tdev - (int)((const KINFO *)b)->ki_p->ki_tdev;
5861556Srgrimes	if (i == 0)
58790143Smarkm		i = ((const KINFO *)a)->ki_p->ki_pid - ((const KINFO *)b)->ki_p->ki_pid;
5881556Srgrimes	return (i);
5891556Srgrimes}
5901556Srgrimes
5911556Srgrimes/*
5921556Srgrimes * ICK (all for getopt), would rather hide the ugliness
5931556Srgrimes * here than taint the main code.
5941556Srgrimes *
5951556Srgrimes *  ps foo -> ps -foo
5961556Srgrimes *  ps 34 -> ps -p34
5971556Srgrimes *
5981556Srgrimes * The old convention that 't' with no trailing tty arg means the users
5991556Srgrimes * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
6001556Srgrimes * feature is available with the option 'T', which takes no argument.
6011556Srgrimes */
6021556Srgrimesstatic char *
60390110Simpkludge_oldps_options(char *s)
6041556Srgrimes{
605102886Sjmallett	int have_fmt;
6061556Srgrimes	size_t len;
6071556Srgrimes	char *newopts, *ns, *cp;
6081556Srgrimes
609102886Sjmallett	/*
610102886Sjmallett	 * If we have an 'o' option, then note it, since we don't want to do
611102886Sjmallett	 * some types of munging.
612102886Sjmallett	 */
613102886Sjmallett	have_fmt = index(s, 'o') != NULL;
614102886Sjmallett
6151556Srgrimes	len = strlen(s);
6161556Srgrimes	if ((newopts = ns = malloc(len + 2)) == NULL)
61797877Sjmallett		errx(1, "malloc failed");
6181556Srgrimes	/*
6191556Srgrimes	 * options begin with '-'
6201556Srgrimes	 */
6211556Srgrimes	if (*s != '-')
6221556Srgrimes		*ns++ = '-';	/* add option flag */
6231556Srgrimes	/*
6241556Srgrimes	 * gaze to end of argv[1]
6251556Srgrimes	 */
6261556Srgrimes	cp = s + len - 1;
6271556Srgrimes	/*
6281556Srgrimes	 * if last letter is a 't' flag with no argument (in the context
6291556Srgrimes	 * of the oldps options -- option string NOT starting with a '-' --
6301556Srgrimes	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
63181743Sbrian	 *
63281743Sbrian	 * However, if a flag accepting a string argument is found in the
63381743Sbrian	 * option string, the remainder of the string is the argument to
63481743Sbrian	 * that flag; do not modify that argument.
6351556Srgrimes	 */
63689909Sru	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
6371556Srgrimes		*cp = 'T';
6381556Srgrimes	else {
6391556Srgrimes		/*
6401556Srgrimes		 * otherwise check for trailing number, which *may* be a
6411556Srgrimes		 * pid.
6421556Srgrimes		 */
6431556Srgrimes		while (cp >= s && isdigit(*cp))
6441556Srgrimes			--cp;
6451556Srgrimes	}
6461556Srgrimes	cp++;
6471556Srgrimes	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
6481556Srgrimes	ns += cp - s;
6491556Srgrimes	/*
6501556Srgrimes	 * if there's a trailing number, and not a preceding 'p' (pid) or
6511556Srgrimes	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
6521556Srgrimes	 */
6538855Srgrimes	if (isdigit(*cp) &&
6547165Sjoerg	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
655102886Sjmallett	    (cp - 1 == s || cp[-2] != 't') && !have_fmt)
6561556Srgrimes		*ns++ = 'p';
6571556Srgrimes	(void)strcpy(ns, cp);		/* and append the number */
6581556Srgrimes
6591556Srgrimes	return (newopts);
6601556Srgrimes}
6611556Srgrimes
6621556Srgrimesstatic void
66390110Simpusage(void)
6641556Srgrimes{
6651556Srgrimes
66626465Scharnier	(void)fprintf(stderr, "%s\n%s\n%s\n",
667105831Srwatson	    "usage: ps [-aChjlmrSTuvwxZ] [-O|o fmt] [-p pid] [-t tty] [-U user]",
66889909Sru	    "          [-M core] [-N system]",
66926465Scharnier	    "       ps [-L]");
6701556Srgrimes	exit(1);
6711556Srgrimes}
672