Home | History | Annotate | Line # | Download | only in ps
ps.c revision 1.23
      1 /*	$NetBSD: ps.c,v 1.23 1998/07/28 05:31:26 mycroft Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1990, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\n\
     39 	The Regents of the University of California.  All rights reserved.\n");
     40 #endif /* not lint */
     41 
     42 #ifndef lint
     43 #if 0
     44 static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
     45 #else
     46 __RCSID("$NetBSD: ps.c,v 1.23 1998/07/28 05:31:26 mycroft Exp $");
     47 #endif
     48 #endif /* not lint */
     49 
     50 #include <sys/param.h>
     51 #include <sys/user.h>
     52 #include <sys/time.h>
     53 #include <sys/resource.h>
     54 #include <sys/proc.h>
     55 #include <sys/stat.h>
     56 #include <sys/ioctl.h>
     57 #include <sys/sysctl.h>
     58 
     59 #include <ctype.h>
     60 #include <err.h>
     61 #include <errno.h>
     62 #include <fcntl.h>
     63 #include <kvm.h>
     64 #include <limits.h>
     65 #include <nlist.h>
     66 #include <paths.h>
     67 #include <stdio.h>
     68 #include <stdlib.h>
     69 #include <string.h>
     70 #include <unistd.h>
     71 
     72 #include "ps.h"
     73 
     74 #ifdef P_PPWAIT
     75 #define NEWVM
     76 #endif
     77 
     78 KINFO *kinfo;
     79 struct varent *vhead, *vtail;
     80 
     81 int	eval;			/* exit value */
     82 int	rawcpu;			/* -C */
     83 int	sumrusage;		/* -S */
     84 int	termwidth;		/* width of screen (0 == infinity) */
     85 int	totwidth;		/* calculated width of requested variables */
     86 
     87 int	needuser, needcomm, needenv, commandonly;
     88 
     89 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
     90 
     91 static char	*kludge_oldps_options __P((char *));
     92 static int	 pscomp __P((const void *, const void *));
     93 static void	 saveuser __P((KINFO *));
     94 static void	 scanvars __P((void));
     95 static void	 usage __P((void));
     96 int		 main __P((int, char *[]));
     97 
     98 char dfmt[] = "pid tt state time command";
     99 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
    100 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
    101 char   o1[] = "pid";
    102 char   o2[] = "tt state time command";
    103 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
    104 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
    105 
    106 kvm_t *kd;
    107 
    108 int
    109 main(argc, argv)
    110 	int argc;
    111 	char *argv[];
    112 {
    113 	struct kinfo_proc *kp;
    114 	struct varent *vent;
    115 	struct winsize ws;
    116 	dev_t ttydev;
    117 	pid_t pid;
    118 	uid_t uid;
    119 	gid_t egid = getegid();
    120 	int all, ch, flag, i, fmt, lineno, nentries;
    121 	int prtheader, wflag, what, xflg;
    122 	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
    123 	const char *ttname;
    124 
    125 	(void)setegid(getgid());
    126 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    127 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    128 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
    129 	     ws.ws_col == 0)
    130 		termwidth = 79;
    131 	else
    132 		termwidth = ws.ws_col - 1;
    133 
    134 	if (argc > 1)
    135 		argv[1] = kludge_oldps_options(argv[1]);
    136 
    137 	all = fmt = prtheader = wflag = xflg = 0;
    138 	pid = -1;
    139 	uid = (uid_t) -1;
    140 	ttydev = NODEV;
    141 	memf = nlistf = swapf = NULL;
    142 	while ((ch = getopt(argc, argv,
    143 	    "acCeghjLlM:mN:O:o:p:rSTt:uvW:wx")) != -1)
    144 		switch((char)ch) {
    145 		case 'a':
    146 			all = 1;
    147 			break;
    148 		case 'c':
    149 			commandonly = 1;
    150 			break;
    151 		case 'e':			/* XXX set ufmt */
    152 			needenv = 1;
    153 			break;
    154 		case 'C':
    155 			rawcpu = 1;
    156 			break;
    157 		case 'g':
    158 			break;			/* no-op */
    159 		case 'h':
    160 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
    161 			break;
    162 		case 'j':
    163 			parsefmt(jfmt);
    164 			fmt = 1;
    165 			jfmt[0] = '\0';
    166 			break;
    167 		case 'L':
    168 			showkey();
    169 			exit(0);
    170 			/* NOTREACHED */
    171 		case 'l':
    172 			parsefmt(lfmt);
    173 			fmt = 1;
    174 			lfmt[0] = '\0';
    175 			break;
    176 		case 'M':
    177 			memf = optarg;
    178 			break;
    179 		case 'm':
    180 			sortby = SORTMEM;
    181 			break;
    182 		case 'N':
    183 			nlistf = optarg;
    184 			break;
    185 		case 'O':
    186 			parsefmt(o1);
    187 			parsefmt(optarg);
    188 			parsefmt(o2);
    189 			o1[0] = o2[0] = '\0';
    190 			fmt = 1;
    191 			break;
    192 		case 'o':
    193 			parsefmt(optarg);
    194 			fmt = 1;
    195 			break;
    196 		case 'p':
    197 			pid = atol(optarg);
    198 			xflg = 1;
    199 			break;
    200 		case 'r':
    201 			sortby = SORTCPU;
    202 			break;
    203 		case 'S':
    204 			sumrusage = 1;
    205 			break;
    206 		case 'T':
    207 			if ((ttname = ttyname(STDIN_FILENO)) == NULL)
    208 				errx(1, "stdin: not a terminal");
    209 			goto tty;
    210 		case 't':
    211 			ttname = optarg;
    212 		tty: {
    213 			struct stat sb;
    214 			char *ttypath, pathbuf[MAXPATHLEN];
    215 
    216 			if (strcmp(optarg, "co") == 0)
    217 				ttypath = _PATH_CONSOLE;
    218 			else if (*optarg != '/')
    219 				(void)snprintf(ttypath = pathbuf,
    220 				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
    221 			else
    222 				ttypath = optarg;
    223 			if (stat(ttypath, &sb) == -1)
    224 				err(1, "%s", ttypath);
    225 			if (!S_ISCHR(sb.st_mode))
    226 				errx(1, "%s: not a terminal", ttypath);
    227 			ttydev = sb.st_rdev;
    228 			break;
    229 		}
    230 		case 'u':
    231 			parsefmt(ufmt);
    232 			sortby = SORTCPU;
    233 			fmt = 1;
    234 			ufmt[0] = '\0';
    235 			break;
    236 		case 'v':
    237 			parsefmt(vfmt);
    238 			sortby = SORTMEM;
    239 			fmt = 1;
    240 			vfmt[0] = '\0';
    241 			break;
    242 		case 'W':
    243 			swapf = optarg;
    244 			break;
    245 		case 'w':
    246 			if (wflag)
    247 				termwidth = UNLIMITED;
    248 			else if (termwidth < 131)
    249 				termwidth = 131;
    250 			wflag++;
    251 			break;
    252 		case 'x':
    253 			xflg = 1;
    254 			break;
    255 		case '?':
    256 		default:
    257 			usage();
    258 		}
    259 	argc -= optind;
    260 	argv += optind;
    261 
    262 #define	BACKWARD_COMPATIBILITY
    263 #ifdef	BACKWARD_COMPATIBILITY
    264 	if (*argv) {
    265 		nlistf = *argv;
    266 		if (*++argv) {
    267 			memf = *argv;
    268 			if (*++argv)
    269 				swapf = *argv;
    270 		}
    271 	}
    272 #endif
    273 	/*
    274 	 * Discard setgid privileges.  If not the running kernel, we toss
    275 	 * them away totally so that bad guys can't print interesting stuff
    276 	 * from kernel memory, otherwise switch back to kmem for the
    277 	 * duration of the kvm_openfiles() call.
    278 	 */
    279 	if (nlistf != NULL || memf != NULL || swapf != NULL)
    280 		(void)setgid(getgid());
    281 	else
    282 		(void)setegid(egid);
    283 
    284 	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
    285 	if (kd == 0)
    286 		errx(1, "%s", errbuf);
    287 
    288 	if (nlistf == NULL && memf == NULL && swapf == NULL)
    289 		(void)setgid(getgid());
    290 
    291 	if (!fmt)
    292 		parsefmt(dfmt);
    293 
    294 	if (!all && ttydev == NODEV && pid == -1)  /* XXX - should be cleaner */
    295 		uid = getuid();
    296 
    297 	/*
    298 	 * scan requested variables, noting what structures are needed,
    299 	 * and adjusting header widths as appropiate.
    300 	 */
    301 	scanvars();
    302 	/*
    303 	 * get proc list
    304 	 */
    305 	if (uid != (uid_t) -1) {
    306 		what = KERN_PROC_UID;
    307 		flag = uid;
    308 	} else if (ttydev != NODEV) {
    309 		what = KERN_PROC_TTY;
    310 		flag = ttydev;
    311 	} else if (pid != -1) {
    312 		what = KERN_PROC_PID;
    313 		flag = pid;
    314 	} else {
    315 		what = KERN_PROC_ALL;
    316 		flag = 0;
    317 	}
    318 	/*
    319 	 * select procs
    320 	 */
    321 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
    322 		errx(1, "%s", kvm_geterr(kd));
    323 	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
    324 		err(1, "%s", "");
    325 	for (i = nentries; --i >= 0; ++kp) {
    326 		kinfo[i].ki_p = kp;
    327 		if (needuser)
    328 			saveuser(&kinfo[i]);
    329 	}
    330 	/*
    331 	 * print header
    332 	 */
    333 	printheader();
    334 	if (nentries == 0) {
    335 		exit(0);
    336 		/* NOTREACHED */
    337 	}
    338 	/*
    339 	 * sort proc list
    340 	 */
    341 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
    342 	/*
    343 	 * for each proc, call each variable output function.
    344 	 */
    345 	for (i = lineno = 0; i < nentries; i++) {
    346 		KINFO *ki = &kinfo[i];
    347 
    348 		if (xflg == 0 && (KI_EPROC(ki)->e_tdev == NODEV ||
    349 		    (KI_PROC(ki)->p_flag & P_CONTROLT ) == 0))
    350 			continue;
    351 		for (vent = vhead; vent; vent = vent->next) {
    352 			(vent->var->oproc)(ki, vent);
    353 			if (vent->next != NULL)
    354 				(void)putchar(' ');
    355 		}
    356 		(void)putchar('\n');
    357 		if (prtheader && lineno++ == prtheader - 4) {
    358 			(void)putchar('\n');
    359 			printheader();
    360 			lineno = 0;
    361 		}
    362 	}
    363 	exit(eval);
    364 	/* NOTREACHED */
    365 }
    366 
    367 static void
    368 scanvars()
    369 {
    370 	struct varent *vent;
    371 	VAR *v;
    372 	int i;
    373 
    374 	for (vent = vhead; vent; vent = vent->next) {
    375 		v = vent->var;
    376 		i = strlen(v->header);
    377 		if (v->width < i)
    378 			v->width = i;
    379 		totwidth += v->width + 1;	/* +1 for space */
    380 		if (v->flag & USER)
    381 			needuser = 1;
    382 		if (v->flag & COMM)
    383 			needcomm = 1;
    384 	}
    385 	totwidth--;
    386 }
    387 
    388 static void
    389 saveuser(ki)
    390 	KINFO *ki;
    391 {
    392 	struct pstats pstats;
    393 	struct usave *usp;
    394 
    395 	usp = &ki->ki_u;
    396 	if (kvm_read(kd, (u_long)&KI_PROC(ki)->p_addr->u_stats,
    397 	    (char *)&pstats, sizeof(pstats)) == sizeof(pstats)) {
    398 		/*
    399 		 * The u-area might be swapped out, and we can't get
    400 		 * at it because we have a crashdump and no swap.
    401 		 * If it's here fill in these fields, otherwise, just
    402 		 * leave them 0.
    403 		 */
    404 		usp->u_start = pstats.p_start;
    405 		usp->u_ru = pstats.p_ru;
    406 		usp->u_cru = pstats.p_cru;
    407 		usp->u_valid = 1;
    408 	} else
    409 		usp->u_valid = 0;
    410 }
    411 
    412 static int
    413 pscomp(a, b)
    414 	const void *a, *b;
    415 {
    416 	int i;
    417 #ifdef NEWVM
    418 #define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
    419 		  KI_EPROC(k)->e_vm.vm_tsize)
    420 #else
    421 #define VSIZE(k) ((k)->ki_p->p_dsize + (k)->ki_p->p_ssize + (k)->ki_e->e_xsize)
    422 #endif
    423 
    424 	if (sortby == SORTCPU)
    425 		return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
    426 	if (sortby == SORTMEM)
    427 		return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
    428 	i =  KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
    429 	if (i == 0)
    430 		i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
    431 	return (i);
    432 }
    433 
    434 /*
    435  * ICK (all for getopt), would rather hide the ugliness
    436  * here than taint the main code.
    437  *
    438  *  ps foo -> ps -foo
    439  *  ps 34 -> ps -p34
    440  *
    441  * The old convention that 't' with no trailing tty arg means the users
    442  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
    443  * feature is available with the option 'T', which takes no argument.
    444  */
    445 static char *
    446 kludge_oldps_options(s)
    447 	char *s;
    448 {
    449 	size_t len;
    450 	char *newopts, *ns, *cp;
    451 
    452 	len = strlen(s);
    453 	if ((newopts = ns = malloc(len + 3)) == NULL)
    454 		err(1, "%s", "");
    455 	/*
    456 	 * options begin with '-'
    457 	 */
    458 	if (*s != '-')
    459 		*ns++ = '-';	/* add option flag */
    460 	/*
    461 	 * gaze to end of argv[1]
    462 	 */
    463 	cp = s + len - 1;
    464 	/*
    465 	 * if last letter is a 't' flag with no argument (in the context
    466 	 * of the oldps options -- option string NOT starting with a '-' --
    467 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
    468 	 */
    469 	if (*cp == 't' && *s != '-')
    470 		*cp = 'T';
    471 	else {
    472 		/*
    473 		 * otherwise check for trailing number, which *may* be a
    474 		 * pid.
    475 		 */
    476 		while (cp >= s && isdigit(*cp))
    477 			--cp;
    478 	}
    479 	cp++;
    480 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
    481 	ns += cp - s;
    482 	/*
    483 	 * if there's a trailing number, and not a preceding 'p' (pid) or
    484 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
    485 	 */
    486 	if (isdigit(*cp) && (cp == s || (cp[-1] != 't' && cp[-1] != 'p' &&
    487 	    (cp - 1 == s || cp[-2] != 't'))))
    488 		*ns++ = 'p';
    489 	/* and append the number */
    490 	(void)strcpy(ns, cp);		/* XXX strcpy is safe */
    491 
    492 	return (newopts);
    493 }
    494 
    495 static void
    496 usage()
    497 {
    498 
    499 	(void)fprintf(stderr,
    500 	    "usage:\t%s\n\t   %s\n\t%s\n",
    501 	    "ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
    502 	    "[-M core] [-N system] [-W swap]",
    503 	    "ps [-L]");
    504 	exit(1);
    505 	/* NOTREACHED */
    506 }
    507