ps.c revision 66377
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
3520420Sstevestatic char const 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
401556Srgrimes#ifndef lint
4136049Scharnier#if 0
4236049Scharnierstatic char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
4336049Scharnier#endif
4436049Scharnierstatic const char rcsid[] =
4550471Speter  "$FreeBSD: head/bin/ps/ps.c 66377 2000-09-26 01:03:16Z brian $";
461556Srgrimes#endif /* not lint */
471556Srgrimes
481556Srgrimes#include <sys/param.h>
493296Sdg#include <sys/user.h>
501556Srgrimes#include <sys/time.h>
511556Srgrimes#include <sys/resource.h>
521556Srgrimes#include <sys/stat.h>
531556Srgrimes#include <sys/ioctl.h>
541556Srgrimes#include <sys/sysctl.h>
551556Srgrimes
561556Srgrimes#include <ctype.h>
571556Srgrimes#include <err.h>
581556Srgrimes#include <errno.h>
591556Srgrimes#include <fcntl.h>
601556Srgrimes#include <kvm.h>
6113514Smpp#include <limits.h>
621556Srgrimes#include <nlist.h>
631556Srgrimes#include <paths.h>
641556Srgrimes#include <stdio.h>
651556Srgrimes#include <stdlib.h>
661556Srgrimes#include <string.h>
671556Srgrimes#include <unistd.h>
6811744Sache#include <locale.h>
6913020Speter#include <pwd.h>
7066377Sbrian#include <utmp.h>
711556Srgrimes
721556Srgrimes#include "ps.h"
731556Srgrimes
7466377Sbrian#define SEP ", \t"		/* username separators */
7566377Sbrian
761556SrgrimesKINFO *kinfo;
771556Srgrimesstruct varent *vhead, *vtail;
781556Srgrimes
791556Srgrimesint	eval;			/* exit value */
8019068Speterint	cflag;			/* -c */
811556Srgrimesint	rawcpu;			/* -C */
821556Srgrimesint	sumrusage;		/* -S */
831556Srgrimesint	termwidth;		/* width of screen (0 == infinity) */
841556Srgrimesint	totwidth;		/* calculated width of requested variables */
851556Srgrimes
861556Srgrimesstatic int needuser, needcomm, needenv;
8731552Sdyson#if defined(LAZY_PS)
8831552Sdysonstatic int forceuread=0;
8931552Sdyson#else
9031552Sdysonstatic int forceuread=1;
9131552Sdyson#endif
921556Srgrimes
931556Srgrimesenum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
941556Srgrimes
951556Srgrimesstatic char	*fmt __P((char **(*)(kvm_t *, const struct kinfo_proc *, int),
961556Srgrimes		    KINFO *, char *, int));
971556Srgrimesstatic char	*kludge_oldps_options __P((char *));
981556Srgrimesstatic int	 pscomp __P((const void *, const void *));
991556Srgrimesstatic void	 saveuser __P((KINFO *));
1001556Srgrimesstatic void	 scanvars __P((void));
10125271Sjkhstatic void	 dynsizevars __P((KINFO *));
10225271Sjkhstatic void	 sizevars __P((void));
1031556Srgrimesstatic void	 usage __P((void));
10466377Sbrianstatic uid_t	*getuids(const char *, int *);
1051556Srgrimes
1061556Srgrimeschar dfmt[] = "pid tt state time command";
1071556Srgrimeschar jfmt[] = "user pid ppid pgid sess jobc state tt time command";
1081556Srgrimeschar lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
1091556Srgrimeschar   o1[] = "pid";
1101556Srgrimeschar   o2[] = "tt state time command";
1111556Srgrimeschar ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
1121556Srgrimeschar vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
1131556Srgrimes
1141556Srgrimeskvm_t *kd;
1151556Srgrimes
1161556Srgrimesint
1171556Srgrimesmain(argc, argv)
1181556Srgrimes	int argc;
1191556Srgrimes	char *argv[];
1201556Srgrimes{
1211556Srgrimes	struct kinfo_proc *kp;
1221556Srgrimes	struct varent *vent;
1231556Srgrimes	struct winsize ws;
1241556Srgrimes	dev_t ttydev;
1251556Srgrimes	pid_t pid;
12666377Sbrian	uid_t *uids;
12737317Sphk	int all, ch, flag, i, fmt, lineno, nentries, dropgid;
12866377Sbrian	int prtheader, wflag, what, xflg, uid, nuids;
12913514Smpp	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
1301556Srgrimes
13111809Sache	(void) setlocale(LC_ALL, "");
13211809Sache
1331556Srgrimes	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1341556Srgrimes	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
1351556Srgrimes	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
1361556Srgrimes	     ws.ws_col == 0)
1371556Srgrimes		termwidth = 79;
1381556Srgrimes	else
1391556Srgrimes		termwidth = ws.ws_col - 1;
1401556Srgrimes
1411556Srgrimes	if (argc > 1)
1421556Srgrimes		argv[1] = kludge_oldps_options(argv[1]);
1431556Srgrimes
1441556Srgrimes	all = fmt = prtheader = wflag = xflg = 0;
1451556Srgrimes	pid = -1;
14666377Sbrian	nuids = 0;
14766377Sbrian	uids = NULL;
1481556Srgrimes	ttydev = NODEV;
14937317Sphk	dropgid = 0;
15037317Sphk	memf = nlistf = swapf = _PATH_DEVNULL;
1511556Srgrimes	while ((ch = getopt(argc, argv,
15231552Sdyson#if defined(LAZY_PS)
15333591Sdima	    "aCcefghjLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
15431552Sdyson#else
15524348Simp	    "aCceghjLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
15631552Sdyson#endif
1571556Srgrimes		switch((char)ch) {
1581556Srgrimes		case 'a':
1591556Srgrimes			all = 1;
1601556Srgrimes			break;
16119068Speter		case 'C':
16219068Speter			rawcpu = 1;
16319068Speter			break;
16419068Speter		case 'c':
16519068Speter			cflag = 1;
16619068Speter			break;
1671556Srgrimes		case 'e':			/* XXX set ufmt */
1681556Srgrimes			needenv = 1;
1691556Srgrimes			break;
1701556Srgrimes		case 'g':
1711556Srgrimes			break;			/* no-op */
1721556Srgrimes		case 'h':
1731556Srgrimes			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
1741556Srgrimes			break;
1751556Srgrimes		case 'j':
1761556Srgrimes			parsefmt(jfmt);
1771556Srgrimes			fmt = 1;
1781556Srgrimes			jfmt[0] = '\0';
1791556Srgrimes			break;
1801556Srgrimes		case 'L':
1811556Srgrimes			showkey();
1821556Srgrimes			exit(0);
1831556Srgrimes		case 'l':
1841556Srgrimes			parsefmt(lfmt);
1851556Srgrimes			fmt = 1;
1861556Srgrimes			lfmt[0] = '\0';
1871556Srgrimes			break;
1881556Srgrimes		case 'M':
1891556Srgrimes			memf = optarg;
19037317Sphk			dropgid = 1;
1911556Srgrimes			break;
1921556Srgrimes		case 'm':
1931556Srgrimes			sortby = SORTMEM;
1941556Srgrimes			break;
1951556Srgrimes		case 'N':
1961556Srgrimes			nlistf = optarg;
19737317Sphk			dropgid = 1;
1981556Srgrimes			break;
1991556Srgrimes		case 'O':
2001556Srgrimes			parsefmt(o1);
2011556Srgrimes			parsefmt(optarg);
2021556Srgrimes			parsefmt(o2);
2031556Srgrimes			o1[0] = o2[0] = '\0';
2041556Srgrimes			fmt = 1;
2051556Srgrimes			break;
2061556Srgrimes		case 'o':
2071556Srgrimes			parsefmt(optarg);
2081556Srgrimes			fmt = 1;
2091556Srgrimes			break;
21031552Sdyson#if defined(LAZY_PS)
21131552Sdyson		case 'f':
21231552Sdyson			if (getuid() == 0 || getgid() == 0)
21331552Sdyson			    forceuread = 1;
21431552Sdyson			break;
21531552Sdyson#endif
2161556Srgrimes		case 'p':
2171556Srgrimes			pid = atol(optarg);
2181556Srgrimes			xflg = 1;
2191556Srgrimes			break;
2201556Srgrimes		case 'r':
2211556Srgrimes			sortby = SORTCPU;
2221556Srgrimes			break;
2231556Srgrimes		case 'S':
2241556Srgrimes			sumrusage = 1;
2251556Srgrimes			break;
2261556Srgrimes		case 'T':
2271556Srgrimes			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
2281556Srgrimes				errx(1, "stdin: not a terminal");
2291556Srgrimes			/* FALLTHROUGH */
2301556Srgrimes		case 't': {
2311556Srgrimes			struct stat sb;
2321556Srgrimes			char *ttypath, pathbuf[MAXPATHLEN];
2331556Srgrimes
2341556Srgrimes			if (strcmp(optarg, "co") == 0)
2351556Srgrimes				ttypath = _PATH_CONSOLE;
2361556Srgrimes			else if (*optarg != '/')
2371556Srgrimes				(void)snprintf(ttypath = pathbuf,
2381556Srgrimes				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
2391556Srgrimes			else
2401556Srgrimes				ttypath = optarg;
2411556Srgrimes			if (stat(ttypath, &sb) == -1)
2421556Srgrimes				err(1, "%s", ttypath);
2431556Srgrimes			if (!S_ISCHR(sb.st_mode))
2441556Srgrimes				errx(1, "%s: not a terminal", ttypath);
2451556Srgrimes			ttydev = sb.st_rdev;
2461556Srgrimes			break;
2471556Srgrimes		}
24813020Speter		case 'U':
24966377Sbrian			uids = getuids(optarg, &nuids);
25013020Speter			xflg++;		/* XXX: intuitive? */
25113020Speter			break;
2521556Srgrimes		case 'u':
2531556Srgrimes			parsefmt(ufmt);
2541556Srgrimes			sortby = SORTCPU;
2551556Srgrimes			fmt = 1;
2561556Srgrimes			ufmt[0] = '\0';
2571556Srgrimes			break;
2581556Srgrimes		case 'v':
2591556Srgrimes			parsefmt(vfmt);
2601556Srgrimes			sortby = SORTMEM;
2611556Srgrimes			fmt = 1;
2621556Srgrimes			vfmt[0] = '\0';
2631556Srgrimes			break;
2641556Srgrimes		case 'W':
2651556Srgrimes			swapf = optarg;
26637317Sphk			dropgid = 1;
2671556Srgrimes			break;
2681556Srgrimes		case 'w':
2691556Srgrimes			if (wflag)
2701556Srgrimes				termwidth = UNLIMITED;
2711556Srgrimes			else if (termwidth < 131)
2721556Srgrimes				termwidth = 131;
2731556Srgrimes			wflag++;
2741556Srgrimes			break;
2751556Srgrimes		case 'x':
2761556Srgrimes			xflg = 1;
2771556Srgrimes			break;
2781556Srgrimes		case '?':
2791556Srgrimes		default:
2801556Srgrimes			usage();
2811556Srgrimes		}
2821556Srgrimes	argc -= optind;
2831556Srgrimes	argv += optind;
2841556Srgrimes
2851556Srgrimes#define	BACKWARD_COMPATIBILITY
2861556Srgrimes#ifdef	BACKWARD_COMPATIBILITY
2871556Srgrimes	if (*argv) {
2881556Srgrimes		nlistf = *argv;
2891556Srgrimes		if (*++argv) {
2901556Srgrimes			memf = *argv;
2911556Srgrimes			if (*++argv)
2921556Srgrimes				swapf = *argv;
2931556Srgrimes		}
2941556Srgrimes	}
2951556Srgrimes#endif
2961556Srgrimes	/*
2971556Srgrimes	 * Discard setgid privileges if not the running kernel so that bad
2981556Srgrimes	 * guys can't print interesting stuff from kernel memory.
2991556Srgrimes	 */
30037317Sphk	if (dropgid) {
3011556Srgrimes		setgid(getgid());
30237317Sphk		setuid(getuid());
30337317Sphk	}
3041556Srgrimes
3051556Srgrimes	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
3061556Srgrimes	if (kd == 0)
3071556Srgrimes		errx(1, "%s", errbuf);
3081556Srgrimes
3091556Srgrimes	if (!fmt)
3101556Srgrimes		parsefmt(dfmt);
3111556Srgrimes
31213020Speter	/* XXX - should be cleaner */
31366377Sbrian	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
31466377Sbrian		if ((uids = malloc(sizeof (*uids))) == NULL)
31566377Sbrian			errx(1, "malloc: %s", strerror(errno));
31666377Sbrian		nuids = 1;
31766377Sbrian		*uids = getuid();
31866377Sbrian	}
3191556Srgrimes
3201556Srgrimes	/*
3211556Srgrimes	 * scan requested variables, noting what structures are needed,
32253170Skris	 * and adjusting header widths as appropriate.
3231556Srgrimes	 */
3241556Srgrimes	scanvars();
3251556Srgrimes	/*
3261556Srgrimes	 * get proc list
3271556Srgrimes	 */
32866377Sbrian	if (nuids == 1) {
3291556Srgrimes		what = KERN_PROC_UID;
33066377Sbrian		flag = *uids;
3311556Srgrimes	} else if (ttydev != NODEV) {
3321556Srgrimes		what = KERN_PROC_TTY;
3331556Srgrimes		flag = ttydev;
3341556Srgrimes	} else if (pid != -1) {
3351556Srgrimes		what = KERN_PROC_PID;
3361556Srgrimes		flag = pid;
3371556Srgrimes	} else {
3381556Srgrimes		what = KERN_PROC_ALL;
3391556Srgrimes		flag = 0;
3401556Srgrimes	}
3411556Srgrimes	/*
3421556Srgrimes	 * select procs
3431556Srgrimes	 */
3441556Srgrimes	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
3451556Srgrimes		errx(1, "%s", kvm_geterr(kd));
3461556Srgrimes	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
3471556Srgrimes		err(1, NULL);
3481556Srgrimes	for (i = nentries; --i >= 0; ++kp) {
3491556Srgrimes		kinfo[i].ki_p = kp;
3501556Srgrimes		if (needuser)
3511556Srgrimes			saveuser(&kinfo[i]);
35225271Sjkh		dynsizevars(&kinfo[i]);
3531556Srgrimes	}
35425271Sjkh
35525271Sjkh	sizevars();
35625271Sjkh
3571556Srgrimes	/*
3581556Srgrimes	 * print header
3591556Srgrimes	 */
3601556Srgrimes	printheader();
3611556Srgrimes	if (nentries == 0)
36262803Swill		exit(1);
3631556Srgrimes	/*
3641556Srgrimes	 * sort proc list
3651556Srgrimes	 */
3661556Srgrimes	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
3671556Srgrimes	/*
3681556Srgrimes	 * for each proc, call each variable output function.
3691556Srgrimes	 */
3701556Srgrimes	for (i = lineno = 0; i < nentries; i++) {
3711556Srgrimes		if (xflg == 0 && (KI_EPROC(&kinfo[i])->e_tdev == NODEV ||
3721556Srgrimes		    (KI_PROC(&kinfo[i])->p_flag & P_CONTROLT ) == 0))
3731556Srgrimes			continue;
37466377Sbrian		if (nuids > 1) {
37566377Sbrian			for (uid = 0; uid < nuids; uid++)
37666377Sbrian				if (KI_EPROC(&kinfo[i])->e_ucred.cr_uid ==
37766377Sbrian				    uids[uid])
37866377Sbrian					break;
37966377Sbrian			if (uid == nuids)
38066377Sbrian				continue;
38166377Sbrian		}
3821556Srgrimes		for (vent = vhead; vent; vent = vent->next) {
3831556Srgrimes			(vent->var->oproc)(&kinfo[i], vent);
3841556Srgrimes			if (vent->next != NULL)
3851556Srgrimes				(void)putchar(' ');
3861556Srgrimes		}
3871556Srgrimes		(void)putchar('\n');
3881556Srgrimes		if (prtheader && lineno++ == prtheader - 4) {
3891556Srgrimes			(void)putchar('\n');
3901556Srgrimes			printheader();
3911556Srgrimes			lineno = 0;
3921556Srgrimes		}
3931556Srgrimes	}
39466377Sbrian	free(uids);
39566377Sbrian
3961556Srgrimes	exit(eval);
3971556Srgrimes}
3981556Srgrimes
39966377Sbrianuid_t *
40066377Sbriangetuids(const char *arg, int *nuids)
40166377Sbrian{
40266377Sbrian	char name[UT_NAMESIZE + 1];
40366377Sbrian	struct passwd *pwd;
40466377Sbrian	uid_t *uids, *moreuids;
40566377Sbrian	int l, alloc;
40666377Sbrian
40766377Sbrian
40866377Sbrian	alloc = 0;
40966377Sbrian	*nuids = 0;
41066377Sbrian	uids = NULL;
41166377Sbrian	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
41266377Sbrian		if (l >= sizeof name) {
41366377Sbrian			warnx("%.*s: name too long", l, arg);
41466377Sbrian			continue;
41566377Sbrian		}
41666377Sbrian		strncpy(name, arg, l);
41766377Sbrian		name[l] = '\0';
41866377Sbrian		if ((pwd = getpwnam(name)) == NULL) {
41966377Sbrian			warnx("%s: no such user", name);
42066377Sbrian			continue;
42166377Sbrian		}
42266377Sbrian		if (*nuids >= alloc) {
42366377Sbrian			alloc = (alloc + 1) << 1;
42466377Sbrian			moreuids = realloc(uids, alloc * sizeof (*uids));
42566377Sbrian			if (moreuids == NULL) {
42666377Sbrian				free(uids);
42766377Sbrian				errx(1, "realloc: %s", strerror(errno));
42866377Sbrian			}
42966377Sbrian			uids = moreuids;
43066377Sbrian		}
43166377Sbrian		uids[(*nuids)++] = pwd->pw_uid;
43266377Sbrian	}
43366377Sbrian	endpwent();
43466377Sbrian
43566377Sbrian	if (!*nuids)
43666377Sbrian		errx(1, "No users specified");
43766377Sbrian
43866377Sbrian	return uids;
43966377Sbrian}
44066377Sbrian
4411556Srgrimesstatic void
4421556Srgrimesscanvars()
4431556Srgrimes{
4441556Srgrimes	struct varent *vent;
4451556Srgrimes	VAR *v;
44625271Sjkh
44725271Sjkh	for (vent = vhead; vent; vent = vent->next) {
44825271Sjkh		v = vent->var;
44925271Sjkh		if (v->flag & DSIZ) {
45025271Sjkh			v->dwidth = v->width;
45125271Sjkh			v->width = 0;
45225271Sjkh		}
45325271Sjkh		if (v->flag & USER)
45425271Sjkh			needuser = 1;
45525271Sjkh		if (v->flag & COMM)
45625271Sjkh			needcomm = 1;
45725271Sjkh	}
45825271Sjkh}
45925271Sjkh
46025271Sjkhstatic void
46125271Sjkhdynsizevars(ki)
46225271Sjkh	KINFO *ki;
46325271Sjkh{
46425271Sjkh	struct varent *vent;
46525271Sjkh	VAR *v;
4661556Srgrimes	int i;
4671556Srgrimes
4681556Srgrimes	for (vent = vhead; vent; vent = vent->next) {
4691556Srgrimes		v = vent->var;
47025271Sjkh		if (!(v->flag & DSIZ))
47125271Sjkh			continue;
47225271Sjkh		i = (v->sproc)( ki);
47325271Sjkh		if (v->width < i)
47425271Sjkh			v->width = i;
47525271Sjkh		if (v->width > v->dwidth)
47625271Sjkh			v->width = v->dwidth;
47725271Sjkh	}
47825271Sjkh}
47925271Sjkh
48025271Sjkhstatic void
48125271Sjkhsizevars()
48225271Sjkh{
48325271Sjkh	struct varent *vent;
48425271Sjkh	VAR *v;
48525271Sjkh	int i;
48625271Sjkh
48725271Sjkh	for (vent = vhead; vent; vent = vent->next) {
48825271Sjkh		v = vent->var;
4891556Srgrimes		i = strlen(v->header);
4901556Srgrimes		if (v->width < i)
4911556Srgrimes			v->width = i;
4921556Srgrimes		totwidth += v->width + 1;	/* +1 for space */
4931556Srgrimes	}
4941556Srgrimes	totwidth--;
4951556Srgrimes}
4961556Srgrimes
4971556Srgrimesstatic char *
4981556Srgrimesfmt(fn, ki, comm, maxlen)
4991556Srgrimes	char **(*fn) __P((kvm_t *, const struct kinfo_proc *, int));
5001556Srgrimes	KINFO *ki;
5011556Srgrimes	char *comm;
5021556Srgrimes	int maxlen;
5031556Srgrimes{
5041556Srgrimes	char *s;
5051556Srgrimes
5061556Srgrimes	if ((s =
5071556Srgrimes	    fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen)) == NULL)
5081556Srgrimes		err(1, NULL);
5091556Srgrimes	return (s);
5101556Srgrimes}
5111556Srgrimes
51231552Sdyson#define UREADOK(ki)	(forceuread || (KI_PROC(ki)->p_flag & P_INMEM))
51331552Sdyson
5141556Srgrimesstatic void
5151556Srgrimessaveuser(ki)
5161556Srgrimes	KINFO *ki;
5171556Srgrimes{
5181556Srgrimes	struct usave *usp;
5191556Srgrimes
5201556Srgrimes	usp = &ki->ki_u;
52145227Swpaul
52253276Speter	if (KI_PROC(ki)->p_flag & P_INMEM) {
5231556Srgrimes		/*
5241556Srgrimes		 * The u-area might be swapped out, and we can't get
5251556Srgrimes		 * at it because we have a crashdump and no swap.
5261556Srgrimes		 * If it's here fill in these fields, otherwise, just
5271556Srgrimes		 * leave them 0.
5281556Srgrimes		 */
52953276Speter		usp->u_start = KI_EPROC(ki)->e_stats.p_start;
53053276Speter		usp->u_ru = KI_EPROC(ki)->e_stats.p_ru;
53153276Speter		usp->u_cru = KI_EPROC(ki)->e_stats.p_cru;
5321556Srgrimes		usp->u_valid = 1;
5331556Srgrimes	} else
5341556Srgrimes		usp->u_valid = 0;
5351556Srgrimes	/*
5361556Srgrimes	 * save arguments if needed
5371556Srgrimes	 */
53853239Sphk	if (needcomm && (UREADOK(ki) || (KI_PROC(ki)->p_args != NULL))) {
53953276Speter		ki->ki_args = fmt(kvm_getargv, ki, KI_PROC(ki)->p_comm,
54053276Speter		    MAXCOMLEN);
54131552Sdyson	} else if (needcomm) {
54253276Speter		ki->ki_args = malloc(strlen(KI_PROC(ki)->p_comm) + 3);
54353276Speter		sprintf(ki->ki_args, "(%s)", KI_PROC(ki)->p_comm);
54453276Speter	} else {
54553276Speter		ki->ki_args = NULL;
54653276Speter	}
54753276Speter	if (needenv && UREADOK(ki)) {
54853276Speter		ki->ki_env = fmt(kvm_getenvv, ki, (char *)NULL, 0);
54953276Speter	} else if (needenv) {
55053276Speter		ki->ki_env = malloc(3);
55153276Speter		strcpy(ki->ki_env, "()");
55253276Speter	} else {
55353276Speter		ki->ki_env = NULL;
55453276Speter	}
5551556Srgrimes}
5561556Srgrimes
5571556Srgrimesstatic int
5581556Srgrimespscomp(a, b)
5591556Srgrimes	const void *a, *b;
5601556Srgrimes{
5611556Srgrimes	int i;
5621556Srgrimes#define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
5631556Srgrimes		  KI_EPROC(k)->e_vm.vm_tsize)
5641556Srgrimes
5651556Srgrimes	if (sortby == SORTCPU)
5661556Srgrimes		return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
5671556Srgrimes	if (sortby == SORTMEM)
5681556Srgrimes		return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
5691556Srgrimes	i =  KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
5701556Srgrimes	if (i == 0)
5711556Srgrimes		i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
5721556Srgrimes	return (i);
5731556Srgrimes}
5741556Srgrimes
5751556Srgrimes/*
5761556Srgrimes * ICK (all for getopt), would rather hide the ugliness
5771556Srgrimes * here than taint the main code.
5781556Srgrimes *
5791556Srgrimes *  ps foo -> ps -foo
5801556Srgrimes *  ps 34 -> ps -p34
5811556Srgrimes *
5821556Srgrimes * The old convention that 't' with no trailing tty arg means the users
5831556Srgrimes * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
5841556Srgrimes * feature is available with the option 'T', which takes no argument.
5851556Srgrimes */
5861556Srgrimesstatic char *
5871556Srgrimeskludge_oldps_options(s)
5881556Srgrimes	char *s;
5891556Srgrimes{
5901556Srgrimes	size_t len;
5911556Srgrimes	char *newopts, *ns, *cp;
5921556Srgrimes
5931556Srgrimes	len = strlen(s);
5941556Srgrimes	if ((newopts = ns = malloc(len + 2)) == NULL)
5951556Srgrimes		err(1, NULL);
5961556Srgrimes	/*
5971556Srgrimes	 * options begin with '-'
5981556Srgrimes	 */
5991556Srgrimes	if (*s != '-')
6001556Srgrimes		*ns++ = '-';	/* add option flag */
6011556Srgrimes	/*
6021556Srgrimes	 * gaze to end of argv[1]
6031556Srgrimes	 */
6041556Srgrimes	cp = s + len - 1;
6051556Srgrimes	/*
6061556Srgrimes	 * if last letter is a 't' flag with no argument (in the context
6071556Srgrimes	 * of the oldps options -- option string NOT starting with a '-' --
6081556Srgrimes	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
6091556Srgrimes	 */
6101556Srgrimes	if (*cp == 't' && *s != '-')
6111556Srgrimes		*cp = 'T';
6121556Srgrimes	else {
6131556Srgrimes		/*
6141556Srgrimes		 * otherwise check for trailing number, which *may* be a
6151556Srgrimes		 * pid.
6161556Srgrimes		 */
6171556Srgrimes		while (cp >= s && isdigit(*cp))
6181556Srgrimes			--cp;
6191556Srgrimes	}
6201556Srgrimes	cp++;
6211556Srgrimes	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
6221556Srgrimes	ns += cp - s;
6231556Srgrimes	/*
6241556Srgrimes	 * if there's a trailing number, and not a preceding 'p' (pid) or
6251556Srgrimes	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
6261556Srgrimes	 */
6278855Srgrimes	if (isdigit(*cp) &&
6287165Sjoerg	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
6297165Sjoerg	    (cp - 1 == s || cp[-2] != 't'))
6301556Srgrimes		*ns++ = 'p';
6311556Srgrimes	(void)strcpy(ns, cp);		/* and append the number */
6321556Srgrimes
6331556Srgrimes	return (newopts);
6341556Srgrimes}
6351556Srgrimes
6361556Srgrimesstatic void
6371556Srgrimesusage()
6381556Srgrimes{
6391556Srgrimes
64026465Scharnier	(void)fprintf(stderr, "%s\n%s\n%s\n",
64126465Scharnier	    "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
64226465Scharnier	    "          [-M core] [-N system] [-W swap]",
64326465Scharnier	    "       ps [-L]");
6441556Srgrimes	exit(1);
6451556Srgrimes}
646