ps.c revision 99110
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
4599110Sobrien#include <sys/cdefs.h>
4699110Sobrien__FBSDID("$FreeBSD: head/bin/ps/ps.c 99110 2002-06-30 05:15:05Z obrien $");
471556Srgrimes
481556Srgrimes#include <sys/param.h>
493296Sdg#include <sys/user.h>
501556Srgrimes#include <sys/stat.h>
511556Srgrimes#include <sys/ioctl.h>
521556Srgrimes#include <sys/sysctl.h>
531556Srgrimes
541556Srgrimes#include <ctype.h>
551556Srgrimes#include <err.h>
561556Srgrimes#include <fcntl.h>
571556Srgrimes#include <kvm.h>
5813514Smpp#include <limits.h>
5973367Sache#include <locale.h>
601556Srgrimes#include <paths.h>
6190143Smarkm#include <pwd.h>
621556Srgrimes#include <stdio.h>
631556Srgrimes#include <stdlib.h>
641556Srgrimes#include <string.h>
651556Srgrimes#include <unistd.h>
6666377Sbrian#include <utmp.h>
671556Srgrimes
6889389Ssobomax#include "lomac.h"
691556Srgrimes#include "ps.h"
701556Srgrimes
7166377Sbrian#define SEP ", \t"		/* username separators */
7266377Sbrian
7390143Smarkmstatic KINFO *kinfo;
7490143Smarkmstruct varent *vhead;
751556Srgrimes
761556Srgrimesint	eval;			/* exit value */
7719068Speterint	cflag;			/* -c */
781556Srgrimesint	rawcpu;			/* -C */
791556Srgrimesint	sumrusage;		/* -S */
801556Srgrimesint	termwidth;		/* width of screen (0 == infinity) */
811556Srgrimesint	totwidth;		/* calculated width of requested variables */
821556Srgrimes
8397966Sjmalletttime_t	now;			/* current time(3) value */
8497966Sjmallett
851556Srgrimesstatic int needuser, needcomm, needenv;
8631552Sdyson#if defined(LAZY_PS)
8731552Sdysonstatic int forceuread=0;
8831552Sdyson#else
8931552Sdysonstatic int forceuread=1;
9031552Sdyson#endif
911556Srgrimes
9290143Smarkmstatic enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
931556Srgrimes
9490143Smarkmstatic const	 char *fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
9590110Simp		    KINFO *, char *, int);
9690110Simpstatic char	*kludge_oldps_options(char *);
9790110Simpstatic int	 pscomp(const void *, const void *);
9890110Simpstatic void	 saveuser(KINFO *);
9990110Simpstatic void	 scanvars(void);
10090110Simpstatic void	 dynsizevars(KINFO *);
10190110Simpstatic void	 sizevars(void);
10290110Simpstatic void	 usage(void);
10366377Sbrianstatic uid_t	*getuids(const char *, int *);
1041556Srgrimes
10597875Sjmallettstatic char dfmt[] = "pid,tt,state,time,command";
10697875Sjmallettstatic char jfmt[] = "user,pid,ppid,pgid,jobc,state,tt,time,command";
10797875Sjmallettstatic char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,tt,time,command";
10890143Smarkmstatic char   o1[] = "pid";
10997875Sjmallettstatic char   o2[] = "tt,state,time,command";
11097875Sjmallettstatic char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
11197875Sjmallettstatic char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,%cpu,%mem,command";
11290143Smarkmstatic char Zfmt[] = "lvl";
1131556Srgrimes
11490143Smarkmstatic kvm_t *kd;
1151556Srgrimes
11698494Ssobomax#if defined(LAZY_PS)
11798494Ssobomax#define PS_ARGS	"aCcefghjLlM:mN:O:o:p:rSTt:U:uvwxZ"
11898494Ssobomax#else
11998494Ssobomax#define PS_ARGS	"aCceghjLlM:mN:O:o:p:rSTt:U:uvwxZ"
12098494Ssobomax#endif
12198494Ssobomax
1221556Srgrimesint
12390110Simpmain(int argc, char *argv[])
1241556Srgrimes{
1251556Srgrimes	struct kinfo_proc *kp;
1261556Srgrimes	struct varent *vent;
1271556Srgrimes	struct winsize ws;
1281556Srgrimes	dev_t ttydev;
1291556Srgrimes	pid_t pid;
13066377Sbrian	uid_t *uids;
13198494Ssobomax	int all, ch, flag, i, _fmt, lineno, nentries, nocludge, dropgid;
13266377Sbrian	int prtheader, wflag, what, xflg, uid, nuids;
13397804Stjr	char *cols;
13490143Smarkm	char errbuf[_POSIX2_LINE_MAX];
13598494Ssobomax	const char *cp, *nlistf, *memf;
1361556Srgrimes
13711809Sache	(void) setlocale(LC_ALL, "");
13897966Sjmallett	/* Set the time to what it is right now. */
13997966Sjmallett	time(&now);
14011809Sache
14197804Stjr	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
14297804Stjr		termwidth = atoi(cols);
14397804Stjr	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1441556Srgrimes	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1451556Srgrimes	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
1461556Srgrimes	     ws.ws_col == 0)
1471556Srgrimes		termwidth = 79;
1481556Srgrimes	else
1491556Srgrimes		termwidth = ws.ws_col - 1;
1501556Srgrimes
15198494Ssobomax	/*
15298494Ssobomax	 * Don't apply a kludge if the first argument is an option taking an
15398494Ssobomax	 * argument
15498494Ssobomax	 */
15598494Ssobomax	if (argc > 1) {
15698494Ssobomax		nocludge = 0;
15798494Ssobomax		if (argv[1][0] == '-') {
15898494Ssobomax			for (cp = PS_ARGS; *cp != '\0'; cp++) {
15998494Ssobomax				if (*cp != ':')
16098494Ssobomax					continue;
16198494Ssobomax				if (*(cp - 1) == argv[1][1]) {
16298494Ssobomax					nocludge = 1;
16398494Ssobomax					break;
16498494Ssobomax				}
16598494Ssobomax			}
16698494Ssobomax		}
16798494Ssobomax		if (nocludge == 0)
16898494Ssobomax			argv[1] = kludge_oldps_options(argv[1]);
16998494Ssobomax	}
1701556Srgrimes
17190143Smarkm	all = _fmt = prtheader = wflag = xflg = 0;
1721556Srgrimes	pid = -1;
17366377Sbrian	nuids = 0;
17466377Sbrian	uids = NULL;
1751556Srgrimes	ttydev = NODEV;
17637317Sphk	dropgid = 0;
17789909Sru	memf = nlistf = _PATH_DEVNULL;
17898494Ssobomax	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
1791556Srgrimes		switch((char)ch) {
1801556Srgrimes		case 'a':
1811556Srgrimes			all = 1;
1821556Srgrimes			break;
18319068Speter		case 'C':
18419068Speter			rawcpu = 1;
18519068Speter			break;
18619068Speter		case 'c':
18719068Speter			cflag = 1;
18819068Speter			break;
1891556Srgrimes		case 'e':			/* XXX set ufmt */
1901556Srgrimes			needenv = 1;
1911556Srgrimes			break;
1921556Srgrimes		case 'g':
1931556Srgrimes			break;			/* no-op */
1941556Srgrimes		case 'h':
1951556Srgrimes			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
1961556Srgrimes			break;
1971556Srgrimes		case 'j':
1981556Srgrimes			parsefmt(jfmt);
19990143Smarkm			_fmt = 1;
2001556Srgrimes			jfmt[0] = '\0';
2011556Srgrimes			break;
2021556Srgrimes		case 'L':
2031556Srgrimes			showkey();
2041556Srgrimes			exit(0);
2051556Srgrimes		case 'l':
2061556Srgrimes			parsefmt(lfmt);
20790143Smarkm			_fmt = 1;
2081556Srgrimes			lfmt[0] = '\0';
2091556Srgrimes			break;
2101556Srgrimes		case 'M':
2111556Srgrimes			memf = optarg;
21237317Sphk			dropgid = 1;
2131556Srgrimes			break;
2141556Srgrimes		case 'm':
2151556Srgrimes			sortby = SORTMEM;
2161556Srgrimes			break;
2171556Srgrimes		case 'N':
2181556Srgrimes			nlistf = optarg;
21937317Sphk			dropgid = 1;
2201556Srgrimes			break;
2211556Srgrimes		case 'O':
2221556Srgrimes			parsefmt(o1);
2231556Srgrimes			parsefmt(optarg);
2241556Srgrimes			parsefmt(o2);
2251556Srgrimes			o1[0] = o2[0] = '\0';
22690143Smarkm			_fmt = 1;
2271556Srgrimes			break;
2281556Srgrimes		case 'o':
2291556Srgrimes			parsefmt(optarg);
23090143Smarkm			_fmt = 1;
2311556Srgrimes			break;
23231552Sdyson#if defined(LAZY_PS)
23331552Sdyson		case 'f':
23431552Sdyson			if (getuid() == 0 || getgid() == 0)
23531552Sdyson			    forceuread = 1;
23631552Sdyson			break;
23731552Sdyson#endif
2381556Srgrimes		case 'p':
2391556Srgrimes			pid = atol(optarg);
2401556Srgrimes			xflg = 1;
2411556Srgrimes			break;
2421556Srgrimes		case 'r':
2431556Srgrimes			sortby = SORTCPU;
2441556Srgrimes			break;
2451556Srgrimes		case 'S':
2461556Srgrimes			sumrusage = 1;
2471556Srgrimes			break;
2481556Srgrimes		case 'T':
2491556Srgrimes			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
2501556Srgrimes				errx(1, "stdin: not a terminal");
2511556Srgrimes			/* FALLTHROUGH */
2521556Srgrimes		case 't': {
2531556Srgrimes			struct stat sb;
25477459Simp			char *ttypath, pathbuf[PATH_MAX];
2551556Srgrimes
2561556Srgrimes			if (strcmp(optarg, "co") == 0)
25790143Smarkm				ttypath = strdup(_PATH_CONSOLE);
2581556Srgrimes			else if (*optarg != '/')
2591556Srgrimes				(void)snprintf(ttypath = pathbuf,
2601556Srgrimes				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
2611556Srgrimes			else
2621556Srgrimes				ttypath = optarg;
2631556Srgrimes			if (stat(ttypath, &sb) == -1)
2641556Srgrimes				err(1, "%s", ttypath);
2651556Srgrimes			if (!S_ISCHR(sb.st_mode))
2661556Srgrimes				errx(1, "%s: not a terminal", ttypath);
2671556Srgrimes			ttydev = sb.st_rdev;
2681556Srgrimes			break;
2691556Srgrimes		}
27013020Speter		case 'U':
27166377Sbrian			uids = getuids(optarg, &nuids);
27213020Speter			xflg++;		/* XXX: intuitive? */
27313020Speter			break;
2741556Srgrimes		case 'u':
2751556Srgrimes			parsefmt(ufmt);
2761556Srgrimes			sortby = SORTCPU;
27790143Smarkm			_fmt = 1;
2781556Srgrimes			ufmt[0] = '\0';
2791556Srgrimes			break;
2801556Srgrimes		case 'v':
2811556Srgrimes			parsefmt(vfmt);
2821556Srgrimes			sortby = SORTMEM;
28390143Smarkm			_fmt = 1;
2841556Srgrimes			vfmt[0] = '\0';
2851556Srgrimes			break;
2861556Srgrimes		case 'w':
2871556Srgrimes			if (wflag)
2881556Srgrimes				termwidth = UNLIMITED;
2891556Srgrimes			else if (termwidth < 131)
2901556Srgrimes				termwidth = 131;
2911556Srgrimes			wflag++;
2921556Srgrimes			break;
2931556Srgrimes		case 'x':
2941556Srgrimes			xflg = 1;
2951556Srgrimes			break;
29686922Sgreen		case 'Z':
29786922Sgreen			parsefmt(Zfmt);
29886922Sgreen			Zfmt[0] = '\0';
29986922Sgreen			break;
3001556Srgrimes		case '?':
3011556Srgrimes		default:
3021556Srgrimes			usage();
3031556Srgrimes		}
3041556Srgrimes	argc -= optind;
3051556Srgrimes	argv += optind;
3061556Srgrimes
3071556Srgrimes#define	BACKWARD_COMPATIBILITY
3081556Srgrimes#ifdef	BACKWARD_COMPATIBILITY
3091556Srgrimes	if (*argv) {
3101556Srgrimes		nlistf = *argv;
3111556Srgrimes		if (*++argv) {
3121556Srgrimes			memf = *argv;
3131556Srgrimes		}
3141556Srgrimes	}
3151556Srgrimes#endif
3161556Srgrimes	/*
3171556Srgrimes	 * Discard setgid privileges if not the running kernel so that bad
3181556Srgrimes	 * guys can't print interesting stuff from kernel memory.
3191556Srgrimes	 */
32037317Sphk	if (dropgid) {
3211556Srgrimes		setgid(getgid());
32237317Sphk		setuid(getuid());
32337317Sphk	}
3241556Srgrimes
32589909Sru	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
3261556Srgrimes	if (kd == 0)
3271556Srgrimes		errx(1, "%s", errbuf);
3281556Srgrimes
32990143Smarkm	if (!_fmt)
3301556Srgrimes		parsefmt(dfmt);
3311556Srgrimes
33213020Speter	/* XXX - should be cleaner */
33366377Sbrian	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
33466377Sbrian		if ((uids = malloc(sizeof (*uids))) == NULL)
33597877Sjmallett			errx(1, "malloc failed");
33666377Sbrian		nuids = 1;
33766377Sbrian		*uids = getuid();
33866377Sbrian	}
3391556Srgrimes
3401556Srgrimes	/*
3411556Srgrimes	 * scan requested variables, noting what structures are needed,
34253170Skris	 * and adjusting header widths as appropriate.
3431556Srgrimes	 */
3441556Srgrimes	scanvars();
3451556Srgrimes	/*
3461556Srgrimes	 * get proc list
3471556Srgrimes	 */
34866377Sbrian	if (nuids == 1) {
3491556Srgrimes		what = KERN_PROC_UID;
35066377Sbrian		flag = *uids;
3511556Srgrimes	} else if (ttydev != NODEV) {
3521556Srgrimes		what = KERN_PROC_TTY;
3531556Srgrimes		flag = ttydev;
3541556Srgrimes	} else if (pid != -1) {
3551556Srgrimes		what = KERN_PROC_PID;
3561556Srgrimes		flag = pid;
3571556Srgrimes	} else {
3581556Srgrimes		what = KERN_PROC_ALL;
3591556Srgrimes		flag = 0;
3601556Srgrimes	}
3611556Srgrimes	/*
3621556Srgrimes	 * select procs
3631556Srgrimes	 */
36482267Speter	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0 || nentries < 0)
3651556Srgrimes		errx(1, "%s", kvm_geterr(kd));
3661556Srgrimes	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
36797877Sjmallett		errx(1, "malloc failed");
3681556Srgrimes	for (i = nentries; --i >= 0; ++kp) {
3691556Srgrimes		kinfo[i].ki_p = kp;
3701556Srgrimes		if (needuser)
3711556Srgrimes			saveuser(&kinfo[i]);
37225271Sjkh		dynsizevars(&kinfo[i]);
3731556Srgrimes	}
37425271Sjkh
37525271Sjkh	sizevars();
37625271Sjkh
3771556Srgrimes	/*
3781556Srgrimes	 * print header
3791556Srgrimes	 */
3801556Srgrimes	printheader();
3811556Srgrimes	if (nentries == 0)
38262803Swill		exit(1);
3831556Srgrimes	/*
3841556Srgrimes	 * sort proc list
3851556Srgrimes	 */
3861556Srgrimes	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
3871556Srgrimes	/*
3881556Srgrimes	 * for each proc, call each variable output function.
3891556Srgrimes	 */
3901556Srgrimes	for (i = lineno = 0; i < nentries; i++) {
39169896Smckusick		if (xflg == 0 && ((&kinfo[i])->ki_p->ki_tdev == NODEV ||
39269896Smckusick		    ((&kinfo[i])->ki_p->ki_flag & P_CONTROLT ) == 0))
3931556Srgrimes			continue;
39466377Sbrian		if (nuids > 1) {
39566377Sbrian			for (uid = 0; uid < nuids; uid++)
39669896Smckusick				if ((&kinfo[i])->ki_p->ki_uid == uids[uid])
39766377Sbrian					break;
39866377Sbrian			if (uid == nuids)
39966377Sbrian				continue;
40066377Sbrian		}
4011556Srgrimes		for (vent = vhead; vent; vent = vent->next) {
4021556Srgrimes			(vent->var->oproc)(&kinfo[i], vent);
4031556Srgrimes			if (vent->next != NULL)
4041556Srgrimes				(void)putchar(' ');
4051556Srgrimes		}
4061556Srgrimes		(void)putchar('\n');
4071556Srgrimes		if (prtheader && lineno++ == prtheader - 4) {
4081556Srgrimes			(void)putchar('\n');
4091556Srgrimes			printheader();
4101556Srgrimes			lineno = 0;
4111556Srgrimes		}
4121556Srgrimes	}
41366377Sbrian	free(uids);
41486922Sgreen	lomac_stop();
41566377Sbrian
4161556Srgrimes	exit(eval);
4171556Srgrimes}
4181556Srgrimes
41966377Sbrianuid_t *
42066377Sbriangetuids(const char *arg, int *nuids)
42166377Sbrian{
42266377Sbrian	char name[UT_NAMESIZE + 1];
42366377Sbrian	struct passwd *pwd;
42466377Sbrian	uid_t *uids, *moreuids;
42590143Smarkm	int alloc;
42690143Smarkm	size_t l;
42766377Sbrian
42866377Sbrian
42966377Sbrian	alloc = 0;
43066377Sbrian	*nuids = 0;
43166377Sbrian	uids = NULL;
43266377Sbrian	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
43366377Sbrian		if (l >= sizeof name) {
43490143Smarkm			warnx("%.*s: name too long", (int)l, arg);
43566377Sbrian			continue;
43666377Sbrian		}
43766377Sbrian		strncpy(name, arg, l);
43866377Sbrian		name[l] = '\0';
43966377Sbrian		if ((pwd = getpwnam(name)) == NULL) {
44066377Sbrian			warnx("%s: no such user", name);
44166377Sbrian			continue;
44266377Sbrian		}
44366377Sbrian		if (*nuids >= alloc) {
44466377Sbrian			alloc = (alloc + 1) << 1;
44566377Sbrian			moreuids = realloc(uids, alloc * sizeof (*uids));
44666377Sbrian			if (moreuids == NULL) {
44766377Sbrian				free(uids);
44897877Sjmallett				errx(1, "realloc failed");
44966377Sbrian			}
45066377Sbrian			uids = moreuids;
45166377Sbrian		}
45266377Sbrian		uids[(*nuids)++] = pwd->pw_uid;
45366377Sbrian	}
45466377Sbrian	endpwent();
45566377Sbrian
45666377Sbrian	if (!*nuids)
45766377Sbrian		errx(1, "No users specified");
45866377Sbrian
45966377Sbrian	return uids;
46066377Sbrian}
46166377Sbrian
4621556Srgrimesstatic void
46390110Simpscanvars(void)
4641556Srgrimes{
4651556Srgrimes	struct varent *vent;
4661556Srgrimes	VAR *v;
46725271Sjkh
46825271Sjkh	for (vent = vhead; vent; vent = vent->next) {
46925271Sjkh		v = vent->var;
47025271Sjkh		if (v->flag & DSIZ) {
47125271Sjkh			v->dwidth = v->width;
47225271Sjkh			v->width = 0;
47325271Sjkh		}
47425271Sjkh		if (v->flag & USER)
47525271Sjkh			needuser = 1;
47625271Sjkh		if (v->flag & COMM)
47725271Sjkh			needcomm = 1;
47825271Sjkh	}
47925271Sjkh}
48025271Sjkh
48125271Sjkhstatic void
48290110Simpdynsizevars(KINFO *ki)
48325271Sjkh{
48425271Sjkh	struct varent *vent;
48525271Sjkh	VAR *v;
4861556Srgrimes	int i;
4871556Srgrimes
4881556Srgrimes	for (vent = vhead; vent; vent = vent->next) {
4891556Srgrimes		v = vent->var;
49025271Sjkh		if (!(v->flag & DSIZ))
49125271Sjkh			continue;
49225271Sjkh		i = (v->sproc)( ki);
49325271Sjkh		if (v->width < i)
49425271Sjkh			v->width = i;
49525271Sjkh		if (v->width > v->dwidth)
49625271Sjkh			v->width = v->dwidth;
49725271Sjkh	}
49825271Sjkh}
49925271Sjkh
50025271Sjkhstatic void
50190110Simpsizevars(void)
50225271Sjkh{
50325271Sjkh	struct varent *vent;
50425271Sjkh	VAR *v;
50525271Sjkh	int i;
50625271Sjkh
50725271Sjkh	for (vent = vhead; vent; vent = vent->next) {
50825271Sjkh		v = vent->var;
5091556Srgrimes		i = strlen(v->header);
5101556Srgrimes		if (v->width < i)
5111556Srgrimes			v->width = i;
5121556Srgrimes		totwidth += v->width + 1;	/* +1 for space */
5131556Srgrimes	}
5141556Srgrimes	totwidth--;
5151556Srgrimes}
5161556Srgrimes
51790143Smarkmstatic const char *
51890110Simpfmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
51990110Simp  char *comm, int maxlen)
5201556Srgrimes{
52190143Smarkm	const char *s;
5221556Srgrimes
52390143Smarkm	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
5241556Srgrimes	return (s);
5251556Srgrimes}
5261556Srgrimes
52771578Sjhb#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
52831552Sdyson
5291556Srgrimesstatic void
53090110Simpsaveuser(KINFO *ki)
5311556Srgrimes{
5321556Srgrimes
53371578Sjhb	if (ki->ki_p->ki_sflag & PS_INMEM) {
5341556Srgrimes		/*
5351556Srgrimes		 * The u-area might be swapped out, and we can't get
5361556Srgrimes		 * at it because we have a crashdump and no swap.
5371556Srgrimes		 * If it's here fill in these fields, otherwise, just
5381556Srgrimes		 * leave them 0.
5391556Srgrimes		 */
54069896Smckusick		ki->ki_valid = 1;
5411556Srgrimes	} else
54269896Smckusick		ki->ki_valid = 0;
5431556Srgrimes	/*
5441556Srgrimes	 * save arguments if needed
5451556Srgrimes	 */
54669896Smckusick	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
54790143Smarkm		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
54890143Smarkm		    MAXCOMLEN));
54931552Sdyson	} else if (needcomm) {
55090143Smarkm		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
55153276Speter	} else {
55253276Speter		ki->ki_args = NULL;
55353276Speter	}
55453276Speter	if (needenv && UREADOK(ki)) {
55590143Smarkm		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
55653276Speter	} else if (needenv) {
55753276Speter		ki->ki_env = malloc(3);
55853276Speter		strcpy(ki->ki_env, "()");
55953276Speter	} else {
56053276Speter		ki->ki_env = NULL;
56153276Speter	}
5621556Srgrimes}
5631556Srgrimes
5641556Srgrimesstatic int
56590110Simppscomp(const void *a, const void *b)
5661556Srgrimes{
5671556Srgrimes	int i;
56869896Smckusick#define VSIZE(k) ((k)->ki_p->ki_dsize + (k)->ki_p->ki_ssize + \
56969896Smckusick		  (k)->ki_p->ki_tsize)
5701556Srgrimes
5711556Srgrimes	if (sortby == SORTCPU)
57290143Smarkm		return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
5731556Srgrimes	if (sortby == SORTMEM)
57490143Smarkm		return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
57590143Smarkm	i =  (int)((const KINFO *)a)->ki_p->ki_tdev - (int)((const KINFO *)b)->ki_p->ki_tdev;
5761556Srgrimes	if (i == 0)
57790143Smarkm		i = ((const KINFO *)a)->ki_p->ki_pid - ((const KINFO *)b)->ki_p->ki_pid;
5781556Srgrimes	return (i);
5791556Srgrimes}
5801556Srgrimes
5811556Srgrimes/*
5821556Srgrimes * ICK (all for getopt), would rather hide the ugliness
5831556Srgrimes * here than taint the main code.
5841556Srgrimes *
5851556Srgrimes *  ps foo -> ps -foo
5861556Srgrimes *  ps 34 -> ps -p34
5871556Srgrimes *
5881556Srgrimes * The old convention that 't' with no trailing tty arg means the users
5891556Srgrimes * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
5901556Srgrimes * feature is available with the option 'T', which takes no argument.
5911556Srgrimes */
5921556Srgrimesstatic char *
59390110Simpkludge_oldps_options(char *s)
5941556Srgrimes{
5951556Srgrimes	size_t len;
5961556Srgrimes	char *newopts, *ns, *cp;
5971556Srgrimes
5981556Srgrimes	len = strlen(s);
5991556Srgrimes	if ((newopts = ns = malloc(len + 2)) == NULL)
60097877Sjmallett		errx(1, "malloc failed");
6011556Srgrimes	/*
6021556Srgrimes	 * options begin with '-'
6031556Srgrimes	 */
6041556Srgrimes	if (*s != '-')
6051556Srgrimes		*ns++ = '-';	/* add option flag */
6061556Srgrimes	/*
6071556Srgrimes	 * gaze to end of argv[1]
6081556Srgrimes	 */
6091556Srgrimes	cp = s + len - 1;
6101556Srgrimes	/*
6111556Srgrimes	 * if last letter is a 't' flag with no argument (in the context
6121556Srgrimes	 * of the oldps options -- option string NOT starting with a '-' --
6131556Srgrimes	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
61481743Sbrian	 *
61581743Sbrian	 * However, if a flag accepting a string argument is found in the
61681743Sbrian	 * option string, the remainder of the string is the argument to
61781743Sbrian	 * that flag; do not modify that argument.
6181556Srgrimes	 */
61989909Sru	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
6201556Srgrimes		*cp = 'T';
6211556Srgrimes	else {
6221556Srgrimes		/*
6231556Srgrimes		 * otherwise check for trailing number, which *may* be a
6241556Srgrimes		 * pid.
6251556Srgrimes		 */
6261556Srgrimes		while (cp >= s && isdigit(*cp))
6271556Srgrimes			--cp;
6281556Srgrimes	}
6291556Srgrimes	cp++;
6301556Srgrimes	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
6311556Srgrimes	ns += cp - s;
6321556Srgrimes	/*
6331556Srgrimes	 * if there's a trailing number, and not a preceding 'p' (pid) or
6341556Srgrimes	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
6351556Srgrimes	 */
6368855Srgrimes	if (isdigit(*cp) &&
6377165Sjoerg	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
6387165Sjoerg	    (cp - 1 == s || cp[-2] != 't'))
6391556Srgrimes		*ns++ = 'p';
6401556Srgrimes	(void)strcpy(ns, cp);		/* and append the number */
6411556Srgrimes
6421556Srgrimes	return (newopts);
6431556Srgrimes}
6441556Srgrimes
6451556Srgrimesstatic void
64690110Simpusage(void)
6471556Srgrimes{
6481556Srgrimes
64926465Scharnier	(void)fprintf(stderr, "%s\n%s\n%s\n",
65026465Scharnier	    "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
65189909Sru	    "          [-M core] [-N system]",
65226465Scharnier	    "       ps [-L]");
6531556Srgrimes	exit(1);
6541556Srgrimes}
655