ps.c revision 98494
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
3490143Smarkm#include <sys/cdefs.h>
3590143Smarkm__FBSDID("$FreeBSD: head/bin/ps/ps.c 98494 2002-06-20 14:55:53Z sobomax $");
3690143Smarkm
371556Srgrimes#ifndef lint
3890143Smarkmstatic const char copyright[] =
391556Srgrimes"@(#) Copyright (c) 1990, 1993, 1994\n\
401556Srgrimes	The Regents of the University of California.  All rights reserved.\n";
411556Srgrimes#endif /* not lint */
421556Srgrimes
4390143Smarkm#if 0
441556Srgrimes#ifndef lint
4536049Scharnierstatic char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
4690143Smarkm#endif /* not lint */
4736049Scharnier#endif
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>
6766377Sbrian#include <utmp.h>
681556Srgrimes
6989389Ssobomax#include "lomac.h"
701556Srgrimes#include "ps.h"
711556Srgrimes
7266377Sbrian#define SEP ", \t"		/* username separators */
7366377Sbrian
7490143Smarkmstatic KINFO *kinfo;
7590143Smarkmstruct varent *vhead;
761556Srgrimes
771556Srgrimesint	eval;			/* exit value */
7819068Speterint	cflag;			/* -c */
791556Srgrimesint	rawcpu;			/* -C */
801556Srgrimesint	sumrusage;		/* -S */
811556Srgrimesint	termwidth;		/* width of screen (0 == infinity) */
821556Srgrimesint	totwidth;		/* calculated width of requested variables */
831556Srgrimes
8497966Sjmalletttime_t	now;			/* current time(3) value */
8597966Sjmallett
861556Srgrimesstatic int needuser, needcomm, needenv;
8731552Sdyson#if defined(LAZY_PS)
8831552Sdysonstatic int forceuread=0;
8931552Sdyson#else
9031552Sdysonstatic int forceuread=1;
9131552Sdyson#endif
921556Srgrimes
9390143Smarkmstatic enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
941556Srgrimes
9590143Smarkmstatic const	 char *fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
9690110Simp		    KINFO *, char *, int);
9790110Simpstatic char	*kludge_oldps_options(char *);
9890110Simpstatic int	 pscomp(const void *, const void *);
9990110Simpstatic void	 saveuser(KINFO *);
10090110Simpstatic void	 scanvars(void);
10190110Simpstatic void	 dynsizevars(KINFO *);
10290110Simpstatic void	 sizevars(void);
10390110Simpstatic void	 usage(void);
10466377Sbrianstatic uid_t	*getuids(const char *, int *);
1051556Srgrimes
10697875Sjmallettstatic char dfmt[] = "pid,tt,state,time,command";
10797875Sjmallettstatic char jfmt[] = "user,pid,ppid,pgid,jobc,state,tt,time,command";
10897875Sjmallettstatic char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,tt,time,command";
10990143Smarkmstatic char   o1[] = "pid";
11097875Sjmallettstatic char   o2[] = "tt,state,time,command";
11197875Sjmallettstatic char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
11297875Sjmallettstatic char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,%cpu,%mem,command";
11390143Smarkmstatic char Zfmt[] = "lvl";
1141556Srgrimes
11590143Smarkmstatic kvm_t *kd;
1161556Srgrimes
11798494Ssobomax#if defined(LAZY_PS)
11898494Ssobomax#define PS_ARGS	"aCcefghjLlM:mN:O:o:p:rSTt:U:uvwxZ"
11998494Ssobomax#else
12098494Ssobomax#define PS_ARGS	"aCceghjLlM:mN:O:o:p:rSTt:U:uvwxZ"
12198494Ssobomax#endif
12298494Ssobomax
1231556Srgrimesint
12490110Simpmain(int argc, char *argv[])
1251556Srgrimes{
1261556Srgrimes	struct kinfo_proc *kp;
1271556Srgrimes	struct varent *vent;
1281556Srgrimes	struct winsize ws;
1291556Srgrimes	dev_t ttydev;
1301556Srgrimes	pid_t pid;
13166377Sbrian	uid_t *uids;
13298494Ssobomax	int all, ch, flag, i, _fmt, lineno, nentries, nocludge, dropgid;
13366377Sbrian	int prtheader, wflag, what, xflg, uid, nuids;
13497804Stjr	char *cols;
13590143Smarkm	char errbuf[_POSIX2_LINE_MAX];
13698494Ssobomax	const char *cp, *nlistf, *memf;
1371556Srgrimes
13811809Sache	(void) setlocale(LC_ALL, "");
13997966Sjmallett	/* Set the time to what it is right now. */
14097966Sjmallett	time(&now);
14111809Sache
14297804Stjr	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
14397804Stjr		termwidth = atoi(cols);
14497804Stjr	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1451556Srgrimes	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1461556Srgrimes	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
1471556Srgrimes	     ws.ws_col == 0)
1481556Srgrimes		termwidth = 79;
1491556Srgrimes	else
1501556Srgrimes		termwidth = ws.ws_col - 1;
1511556Srgrimes
15298494Ssobomax	/*
15398494Ssobomax	 * Don't apply a kludge if the first argument is an option taking an
15498494Ssobomax	 * argument
15598494Ssobomax	 */
15698494Ssobomax	if (argc > 1) {
15798494Ssobomax		nocludge = 0;
15898494Ssobomax		if (argv[1][0] == '-') {
15998494Ssobomax			for (cp = PS_ARGS; *cp != '\0'; cp++) {
16098494Ssobomax				if (*cp != ':')
16198494Ssobomax					continue;
16298494Ssobomax				if (*(cp - 1) == argv[1][1]) {
16398494Ssobomax					nocludge = 1;
16498494Ssobomax					break;
16598494Ssobomax				}
16698494Ssobomax			}
16798494Ssobomax		}
16898494Ssobomax		if (nocludge == 0)
16998494Ssobomax			argv[1] = kludge_oldps_options(argv[1]);
17098494Ssobomax	}
1711556Srgrimes
17290143Smarkm	all = _fmt = prtheader = wflag = xflg = 0;
1731556Srgrimes	pid = -1;
17466377Sbrian	nuids = 0;
17566377Sbrian	uids = NULL;
1761556Srgrimes	ttydev = NODEV;
17737317Sphk	dropgid = 0;
17889909Sru	memf = nlistf = _PATH_DEVNULL;
17998494Ssobomax	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
1801556Srgrimes		switch((char)ch) {
1811556Srgrimes		case 'a':
1821556Srgrimes			all = 1;
1831556Srgrimes			break;
18419068Speter		case 'C':
18519068Speter			rawcpu = 1;
18619068Speter			break;
18719068Speter		case 'c':
18819068Speter			cflag = 1;
18919068Speter			break;
1901556Srgrimes		case 'e':			/* XXX set ufmt */
1911556Srgrimes			needenv = 1;
1921556Srgrimes			break;
1931556Srgrimes		case 'g':
1941556Srgrimes			break;			/* no-op */
1951556Srgrimes		case 'h':
1961556Srgrimes			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
1971556Srgrimes			break;
1981556Srgrimes		case 'j':
1991556Srgrimes			parsefmt(jfmt);
20090143Smarkm			_fmt = 1;
2011556Srgrimes			jfmt[0] = '\0';
2021556Srgrimes			break;
2031556Srgrimes		case 'L':
2041556Srgrimes			showkey();
2051556Srgrimes			exit(0);
2061556Srgrimes		case 'l':
2071556Srgrimes			parsefmt(lfmt);
20890143Smarkm			_fmt = 1;
2091556Srgrimes			lfmt[0] = '\0';
2101556Srgrimes			break;
2111556Srgrimes		case 'M':
2121556Srgrimes			memf = optarg;
21337317Sphk			dropgid = 1;
2141556Srgrimes			break;
2151556Srgrimes		case 'm':
2161556Srgrimes			sortby = SORTMEM;
2171556Srgrimes			break;
2181556Srgrimes		case 'N':
2191556Srgrimes			nlistf = optarg;
22037317Sphk			dropgid = 1;
2211556Srgrimes			break;
2221556Srgrimes		case 'O':
2231556Srgrimes			parsefmt(o1);
2241556Srgrimes			parsefmt(optarg);
2251556Srgrimes			parsefmt(o2);
2261556Srgrimes			o1[0] = o2[0] = '\0';
22790143Smarkm			_fmt = 1;
2281556Srgrimes			break;
2291556Srgrimes		case 'o':
2301556Srgrimes			parsefmt(optarg);
23190143Smarkm			_fmt = 1;
2321556Srgrimes			break;
23331552Sdyson#if defined(LAZY_PS)
23431552Sdyson		case 'f':
23531552Sdyson			if (getuid() == 0 || getgid() == 0)
23631552Sdyson			    forceuread = 1;
23731552Sdyson			break;
23831552Sdyson#endif
2391556Srgrimes		case 'p':
2401556Srgrimes			pid = atol(optarg);
2411556Srgrimes			xflg = 1;
2421556Srgrimes			break;
2431556Srgrimes		case 'r':
2441556Srgrimes			sortby = SORTCPU;
2451556Srgrimes			break;
2461556Srgrimes		case 'S':
2471556Srgrimes			sumrusage = 1;
2481556Srgrimes			break;
2491556Srgrimes		case 'T':
2501556Srgrimes			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
2511556Srgrimes				errx(1, "stdin: not a terminal");
2521556Srgrimes			/* FALLTHROUGH */
2531556Srgrimes		case 't': {
2541556Srgrimes			struct stat sb;
25577459Simp			char *ttypath, pathbuf[PATH_MAX];
2561556Srgrimes
2571556Srgrimes			if (strcmp(optarg, "co") == 0)
25890143Smarkm				ttypath = strdup(_PATH_CONSOLE);
2591556Srgrimes			else if (*optarg != '/')
2601556Srgrimes				(void)snprintf(ttypath = pathbuf,
2611556Srgrimes				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
2621556Srgrimes			else
2631556Srgrimes				ttypath = optarg;
2641556Srgrimes			if (stat(ttypath, &sb) == -1)
2651556Srgrimes				err(1, "%s", ttypath);
2661556Srgrimes			if (!S_ISCHR(sb.st_mode))
2671556Srgrimes				errx(1, "%s: not a terminal", ttypath);
2681556Srgrimes			ttydev = sb.st_rdev;
2691556Srgrimes			break;
2701556Srgrimes		}
27113020Speter		case 'U':
27266377Sbrian			uids = getuids(optarg, &nuids);
27313020Speter			xflg++;		/* XXX: intuitive? */
27413020Speter			break;
2751556Srgrimes		case 'u':
2761556Srgrimes			parsefmt(ufmt);
2771556Srgrimes			sortby = SORTCPU;
27890143Smarkm			_fmt = 1;
2791556Srgrimes			ufmt[0] = '\0';
2801556Srgrimes			break;
2811556Srgrimes		case 'v':
2821556Srgrimes			parsefmt(vfmt);
2831556Srgrimes			sortby = SORTMEM;
28490143Smarkm			_fmt = 1;
2851556Srgrimes			vfmt[0] = '\0';
2861556Srgrimes			break;
2871556Srgrimes		case 'w':
2881556Srgrimes			if (wflag)
2891556Srgrimes				termwidth = UNLIMITED;
2901556Srgrimes			else if (termwidth < 131)
2911556Srgrimes				termwidth = 131;
2921556Srgrimes			wflag++;
2931556Srgrimes			break;
2941556Srgrimes		case 'x':
2951556Srgrimes			xflg = 1;
2961556Srgrimes			break;
29786922Sgreen		case 'Z':
29886922Sgreen			parsefmt(Zfmt);
29986922Sgreen			Zfmt[0] = '\0';
30086922Sgreen			break;
3011556Srgrimes		case '?':
3021556Srgrimes		default:
3031556Srgrimes			usage();
3041556Srgrimes		}
3051556Srgrimes	argc -= optind;
3061556Srgrimes	argv += optind;
3071556Srgrimes
3081556Srgrimes#define	BACKWARD_COMPATIBILITY
3091556Srgrimes#ifdef	BACKWARD_COMPATIBILITY
3101556Srgrimes	if (*argv) {
3111556Srgrimes		nlistf = *argv;
3121556Srgrimes		if (*++argv) {
3131556Srgrimes			memf = *argv;
3141556Srgrimes		}
3151556Srgrimes	}
3161556Srgrimes#endif
3171556Srgrimes	/*
3181556Srgrimes	 * Discard setgid privileges if not the running kernel so that bad
3191556Srgrimes	 * guys can't print interesting stuff from kernel memory.
3201556Srgrimes	 */
32137317Sphk	if (dropgid) {
3221556Srgrimes		setgid(getgid());
32337317Sphk		setuid(getuid());
32437317Sphk	}
3251556Srgrimes
32689909Sru	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
3271556Srgrimes	if (kd == 0)
3281556Srgrimes		errx(1, "%s", errbuf);
3291556Srgrimes
33090143Smarkm	if (!_fmt)
3311556Srgrimes		parsefmt(dfmt);
3321556Srgrimes
33313020Speter	/* XXX - should be cleaner */
33466377Sbrian	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
33566377Sbrian		if ((uids = malloc(sizeof (*uids))) == NULL)
33697877Sjmallett			errx(1, "malloc failed");
33766377Sbrian		nuids = 1;
33866377Sbrian		*uids = getuid();
33966377Sbrian	}
3401556Srgrimes
3411556Srgrimes	/*
3421556Srgrimes	 * scan requested variables, noting what structures are needed,
34353170Skris	 * and adjusting header widths as appropriate.
3441556Srgrimes	 */
3451556Srgrimes	scanvars();
3461556Srgrimes	/*
3471556Srgrimes	 * get proc list
3481556Srgrimes	 */
34966377Sbrian	if (nuids == 1) {
3501556Srgrimes		what = KERN_PROC_UID;
35166377Sbrian		flag = *uids;
3521556Srgrimes	} else if (ttydev != NODEV) {
3531556Srgrimes		what = KERN_PROC_TTY;
3541556Srgrimes		flag = ttydev;
3551556Srgrimes	} else if (pid != -1) {
3561556Srgrimes		what = KERN_PROC_PID;
3571556Srgrimes		flag = pid;
3581556Srgrimes	} else {
3591556Srgrimes		what = KERN_PROC_ALL;
3601556Srgrimes		flag = 0;
3611556Srgrimes	}
3621556Srgrimes	/*
3631556Srgrimes	 * select procs
3641556Srgrimes	 */
36582267Speter	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0 || nentries < 0)
3661556Srgrimes		errx(1, "%s", kvm_geterr(kd));
3671556Srgrimes	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
36897877Sjmallett		errx(1, "malloc failed");
3691556Srgrimes	for (i = nentries; --i >= 0; ++kp) {
3701556Srgrimes		kinfo[i].ki_p = kp;
3711556Srgrimes		if (needuser)
3721556Srgrimes			saveuser(&kinfo[i]);
37325271Sjkh		dynsizevars(&kinfo[i]);
3741556Srgrimes	}
37525271Sjkh
37625271Sjkh	sizevars();
37725271Sjkh
3781556Srgrimes	/*
3791556Srgrimes	 * print header
3801556Srgrimes	 */
3811556Srgrimes	printheader();
3821556Srgrimes	if (nentries == 0)
38362803Swill		exit(1);
3841556Srgrimes	/*
3851556Srgrimes	 * sort proc list
3861556Srgrimes	 */
3871556Srgrimes	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
3881556Srgrimes	/*
3891556Srgrimes	 * for each proc, call each variable output function.
3901556Srgrimes	 */
3911556Srgrimes	for (i = lineno = 0; i < nentries; i++) {
39269896Smckusick		if (xflg == 0 && ((&kinfo[i])->ki_p->ki_tdev == NODEV ||
39369896Smckusick		    ((&kinfo[i])->ki_p->ki_flag & P_CONTROLT ) == 0))
3941556Srgrimes			continue;
39566377Sbrian		if (nuids > 1) {
39666377Sbrian			for (uid = 0; uid < nuids; uid++)
39769896Smckusick				if ((&kinfo[i])->ki_p->ki_uid == uids[uid])
39866377Sbrian					break;
39966377Sbrian			if (uid == nuids)
40066377Sbrian				continue;
40166377Sbrian		}
4021556Srgrimes		for (vent = vhead; vent; vent = vent->next) {
4031556Srgrimes			(vent->var->oproc)(&kinfo[i], vent);
4041556Srgrimes			if (vent->next != NULL)
4051556Srgrimes				(void)putchar(' ');
4061556Srgrimes		}
4071556Srgrimes		(void)putchar('\n');
4081556Srgrimes		if (prtheader && lineno++ == prtheader - 4) {
4091556Srgrimes			(void)putchar('\n');
4101556Srgrimes			printheader();
4111556Srgrimes			lineno = 0;
4121556Srgrimes		}
4131556Srgrimes	}
41466377Sbrian	free(uids);
41586922Sgreen	lomac_stop();
41666377Sbrian
4171556Srgrimes	exit(eval);
4181556Srgrimes}
4191556Srgrimes
42066377Sbrianuid_t *
42166377Sbriangetuids(const char *arg, int *nuids)
42266377Sbrian{
42366377Sbrian	char name[UT_NAMESIZE + 1];
42466377Sbrian	struct passwd *pwd;
42566377Sbrian	uid_t *uids, *moreuids;
42690143Smarkm	int alloc;
42790143Smarkm	size_t l;
42866377Sbrian
42966377Sbrian
43066377Sbrian	alloc = 0;
43166377Sbrian	*nuids = 0;
43266377Sbrian	uids = NULL;
43366377Sbrian	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
43466377Sbrian		if (l >= sizeof name) {
43590143Smarkm			warnx("%.*s: name too long", (int)l, arg);
43666377Sbrian			continue;
43766377Sbrian		}
43866377Sbrian		strncpy(name, arg, l);
43966377Sbrian		name[l] = '\0';
44066377Sbrian		if ((pwd = getpwnam(name)) == NULL) {
44166377Sbrian			warnx("%s: no such user", name);
44266377Sbrian			continue;
44366377Sbrian		}
44466377Sbrian		if (*nuids >= alloc) {
44566377Sbrian			alloc = (alloc + 1) << 1;
44666377Sbrian			moreuids = realloc(uids, alloc * sizeof (*uids));
44766377Sbrian			if (moreuids == NULL) {
44866377Sbrian				free(uids);
44997877Sjmallett				errx(1, "realloc failed");
45066377Sbrian			}
45166377Sbrian			uids = moreuids;
45266377Sbrian		}
45366377Sbrian		uids[(*nuids)++] = pwd->pw_uid;
45466377Sbrian	}
45566377Sbrian	endpwent();
45666377Sbrian
45766377Sbrian	if (!*nuids)
45866377Sbrian		errx(1, "No users specified");
45966377Sbrian
46066377Sbrian	return uids;
46166377Sbrian}
46266377Sbrian
4631556Srgrimesstatic void
46490110Simpscanvars(void)
4651556Srgrimes{
4661556Srgrimes	struct varent *vent;
4671556Srgrimes	VAR *v;
46825271Sjkh
46925271Sjkh	for (vent = vhead; vent; vent = vent->next) {
47025271Sjkh		v = vent->var;
47125271Sjkh		if (v->flag & DSIZ) {
47225271Sjkh			v->dwidth = v->width;
47325271Sjkh			v->width = 0;
47425271Sjkh		}
47525271Sjkh		if (v->flag & USER)
47625271Sjkh			needuser = 1;
47725271Sjkh		if (v->flag & COMM)
47825271Sjkh			needcomm = 1;
47925271Sjkh	}
48025271Sjkh}
48125271Sjkh
48225271Sjkhstatic void
48390110Simpdynsizevars(KINFO *ki)
48425271Sjkh{
48525271Sjkh	struct varent *vent;
48625271Sjkh	VAR *v;
4871556Srgrimes	int i;
4881556Srgrimes
4891556Srgrimes	for (vent = vhead; vent; vent = vent->next) {
4901556Srgrimes		v = vent->var;
49125271Sjkh		if (!(v->flag & DSIZ))
49225271Sjkh			continue;
49325271Sjkh		i = (v->sproc)( ki);
49425271Sjkh		if (v->width < i)
49525271Sjkh			v->width = i;
49625271Sjkh		if (v->width > v->dwidth)
49725271Sjkh			v->width = v->dwidth;
49825271Sjkh	}
49925271Sjkh}
50025271Sjkh
50125271Sjkhstatic void
50290110Simpsizevars(void)
50325271Sjkh{
50425271Sjkh	struct varent *vent;
50525271Sjkh	VAR *v;
50625271Sjkh	int i;
50725271Sjkh
50825271Sjkh	for (vent = vhead; vent; vent = vent->next) {
50925271Sjkh		v = vent->var;
5101556Srgrimes		i = strlen(v->header);
5111556Srgrimes		if (v->width < i)
5121556Srgrimes			v->width = i;
5131556Srgrimes		totwidth += v->width + 1;	/* +1 for space */
5141556Srgrimes	}
5151556Srgrimes	totwidth--;
5161556Srgrimes}
5171556Srgrimes
51890143Smarkmstatic const char *
51990110Simpfmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
52090110Simp  char *comm, int maxlen)
5211556Srgrimes{
52290143Smarkm	const char *s;
5231556Srgrimes
52490143Smarkm	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
5251556Srgrimes	return (s);
5261556Srgrimes}
5271556Srgrimes
52871578Sjhb#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
52931552Sdyson
5301556Srgrimesstatic void
53190110Simpsaveuser(KINFO *ki)
5321556Srgrimes{
5331556Srgrimes
53471578Sjhb	if (ki->ki_p->ki_sflag & PS_INMEM) {
5351556Srgrimes		/*
5361556Srgrimes		 * The u-area might be swapped out, and we can't get
5371556Srgrimes		 * at it because we have a crashdump and no swap.
5381556Srgrimes		 * If it's here fill in these fields, otherwise, just
5391556Srgrimes		 * leave them 0.
5401556Srgrimes		 */
54169896Smckusick		ki->ki_valid = 1;
5421556Srgrimes	} else
54369896Smckusick		ki->ki_valid = 0;
5441556Srgrimes	/*
5451556Srgrimes	 * save arguments if needed
5461556Srgrimes	 */
54769896Smckusick	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
54890143Smarkm		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
54990143Smarkm		    MAXCOMLEN));
55031552Sdyson	} else if (needcomm) {
55190143Smarkm		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
55253276Speter	} else {
55353276Speter		ki->ki_args = NULL;
55453276Speter	}
55553276Speter	if (needenv && UREADOK(ki)) {
55690143Smarkm		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
55753276Speter	} else if (needenv) {
55853276Speter		ki->ki_env = malloc(3);
55953276Speter		strcpy(ki->ki_env, "()");
56053276Speter	} else {
56153276Speter		ki->ki_env = NULL;
56253276Speter	}
5631556Srgrimes}
5641556Srgrimes
5651556Srgrimesstatic int
56690110Simppscomp(const void *a, const void *b)
5671556Srgrimes{
5681556Srgrimes	int i;
56969896Smckusick#define VSIZE(k) ((k)->ki_p->ki_dsize + (k)->ki_p->ki_ssize + \
57069896Smckusick		  (k)->ki_p->ki_tsize)
5711556Srgrimes
5721556Srgrimes	if (sortby == SORTCPU)
57390143Smarkm		return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
5741556Srgrimes	if (sortby == SORTMEM)
57590143Smarkm		return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
57690143Smarkm	i =  (int)((const KINFO *)a)->ki_p->ki_tdev - (int)((const KINFO *)b)->ki_p->ki_tdev;
5771556Srgrimes	if (i == 0)
57890143Smarkm		i = ((const KINFO *)a)->ki_p->ki_pid - ((const KINFO *)b)->ki_p->ki_pid;
5791556Srgrimes	return (i);
5801556Srgrimes}
5811556Srgrimes
5821556Srgrimes/*
5831556Srgrimes * ICK (all for getopt), would rather hide the ugliness
5841556Srgrimes * here than taint the main code.
5851556Srgrimes *
5861556Srgrimes *  ps foo -> ps -foo
5871556Srgrimes *  ps 34 -> ps -p34
5881556Srgrimes *
5891556Srgrimes * The old convention that 't' with no trailing tty arg means the users
5901556Srgrimes * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
5911556Srgrimes * feature is available with the option 'T', which takes no argument.
5921556Srgrimes */
5931556Srgrimesstatic char *
59490110Simpkludge_oldps_options(char *s)
5951556Srgrimes{
5961556Srgrimes	size_t len;
5971556Srgrimes	char *newopts, *ns, *cp;
5981556Srgrimes
5991556Srgrimes	len = strlen(s);
6001556Srgrimes	if ((newopts = ns = malloc(len + 2)) == NULL)
60197877Sjmallett		errx(1, "malloc failed");
6021556Srgrimes	/*
6031556Srgrimes	 * options begin with '-'
6041556Srgrimes	 */
6051556Srgrimes	if (*s != '-')
6061556Srgrimes		*ns++ = '-';	/* add option flag */
6071556Srgrimes	/*
6081556Srgrimes	 * gaze to end of argv[1]
6091556Srgrimes	 */
6101556Srgrimes	cp = s + len - 1;
6111556Srgrimes	/*
6121556Srgrimes	 * if last letter is a 't' flag with no argument (in the context
6131556Srgrimes	 * of the oldps options -- option string NOT starting with a '-' --
6141556Srgrimes	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
61581743Sbrian	 *
61681743Sbrian	 * However, if a flag accepting a string argument is found in the
61781743Sbrian	 * option string, the remainder of the string is the argument to
61881743Sbrian	 * that flag; do not modify that argument.
6191556Srgrimes	 */
62089909Sru	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
6211556Srgrimes		*cp = 'T';
6221556Srgrimes	else {
6231556Srgrimes		/*
6241556Srgrimes		 * otherwise check for trailing number, which *may* be a
6251556Srgrimes		 * pid.
6261556Srgrimes		 */
6271556Srgrimes		while (cp >= s && isdigit(*cp))
6281556Srgrimes			--cp;
6291556Srgrimes	}
6301556Srgrimes	cp++;
6311556Srgrimes	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
6321556Srgrimes	ns += cp - s;
6331556Srgrimes	/*
6341556Srgrimes	 * if there's a trailing number, and not a preceding 'p' (pid) or
6351556Srgrimes	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
6361556Srgrimes	 */
6378855Srgrimes	if (isdigit(*cp) &&
6387165Sjoerg	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
6397165Sjoerg	    (cp - 1 == s || cp[-2] != 't'))
6401556Srgrimes		*ns++ = 'p';
6411556Srgrimes	(void)strcpy(ns, cp);		/* and append the number */
6421556Srgrimes
6431556Srgrimes	return (newopts);
6441556Srgrimes}
6451556Srgrimes
6461556Srgrimesstatic void
64790110Simpusage(void)
6481556Srgrimes{
6491556Srgrimes
65026465Scharnier	(void)fprintf(stderr, "%s\n%s\n%s\n",
65126465Scharnier	    "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
65289909Sru	    "          [-M core] [-N system]",
65326465Scharnier	    "       ps [-L]");
6541556Srgrimes	exit(1);
6551556Srgrimes}
656