Home | History | Annotate | Line # | Download | only in ps
ps.c revision 1.21
      1 /*	$NetBSD: ps.c,v 1.21 1998/07/06 07:50:18 mrg 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.21 1998/07/06 07:50:18 mrg 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 
    124 	(void)setegid(getgid());
    125 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    126 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    127 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
    128 	     ws.ws_col == 0)
    129 		termwidth = 79;
    130 	else
    131 		termwidth = ws.ws_col - 1;
    132 
    133 	if (argc > 1)
    134 		argv[1] = kludge_oldps_options(argv[1]);
    135 
    136 	all = fmt = prtheader = wflag = xflg = 0;
    137 	pid = -1;
    138 	uid = (uid_t) -1;
    139 	ttydev = NODEV;
    140 	memf = nlistf = swapf = NULL;
    141 	while ((ch = getopt(argc, argv,
    142 	    "acCeghjLlM:mN:O:o:p:rSTt:uvW:wx")) != -1)
    143 		switch((char)ch) {
    144 		case 'a':
    145 			all = 1;
    146 			break;
    147 		case 'c':
    148 			commandonly = 1;
    149 			break;
    150 		case 'e':			/* XXX set ufmt */
    151 			needenv = 1;
    152 			break;
    153 		case 'C':
    154 			rawcpu = 1;
    155 			break;
    156 		case 'g':
    157 			break;			/* no-op */
    158 		case 'h':
    159 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
    160 			break;
    161 		case 'j':
    162 			parsefmt(jfmt);
    163 			fmt = 1;
    164 			jfmt[0] = '\0';
    165 			break;
    166 		case 'L':
    167 			showkey();
    168 			exit(0);
    169 		case 'l':
    170 			parsefmt(lfmt);
    171 			fmt = 1;
    172 			lfmt[0] = '\0';
    173 			break;
    174 		case 'M':
    175 			memf = optarg;
    176 			break;
    177 		case 'm':
    178 			sortby = SORTMEM;
    179 			break;
    180 		case 'N':
    181 			nlistf = optarg;
    182 			break;
    183 		case 'O':
    184 			parsefmt(o1);
    185 			parsefmt(optarg);
    186 			parsefmt(o2);
    187 			o1[0] = o2[0] = '\0';
    188 			fmt = 1;
    189 			break;
    190 		case 'o':
    191 			parsefmt(optarg);
    192 			fmt = 1;
    193 			break;
    194 		case 'p':
    195 			pid = atol(optarg);
    196 			xflg = 1;
    197 			break;
    198 		case 'r':
    199 			sortby = SORTCPU;
    200 			break;
    201 		case 'S':
    202 			sumrusage = 1;
    203 			break;
    204 		case 'T':
    205 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
    206 				errx(1, "stdin: not a terminal");
    207 			/* FALLTHROUGH */
    208 		case 't': {
    209 			struct stat sb;
    210 			char *ttypath, pathbuf[MAXPATHLEN];
    211 
    212 			if (strcmp(optarg, "co") == 0)
    213 				ttypath = _PATH_CONSOLE;
    214 			else if (*optarg != '/')
    215 				(void)snprintf(ttypath = pathbuf,
    216 				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
    217 			else
    218 				ttypath = optarg;
    219 			if (stat(ttypath, &sb) == -1)
    220 				err(1, "%s", ttypath);
    221 			if (!S_ISCHR(sb.st_mode))
    222 				errx(1, "%s: not a terminal", ttypath);
    223 			ttydev = sb.st_rdev;
    224 			break;
    225 		}
    226 		case 'u':
    227 			parsefmt(ufmt);
    228 			sortby = SORTCPU;
    229 			fmt = 1;
    230 			ufmt[0] = '\0';
    231 			break;
    232 		case 'v':
    233 			parsefmt(vfmt);
    234 			sortby = SORTMEM;
    235 			fmt = 1;
    236 			vfmt[0] = '\0';
    237 			break;
    238 		case 'W':
    239 			swapf = optarg;
    240 			break;
    241 		case 'w':
    242 			if (wflag)
    243 				termwidth = UNLIMITED;
    244 			else if (termwidth < 131)
    245 				termwidth = 131;
    246 			wflag++;
    247 			break;
    248 		case 'x':
    249 			xflg = 1;
    250 			break;
    251 		case '?':
    252 		default:
    253 			usage();
    254 		}
    255 	argc -= optind;
    256 	argv += optind;
    257 
    258 #define	BACKWARD_COMPATIBILITY
    259 #ifdef	BACKWARD_COMPATIBILITY
    260 	if (*argv) {
    261 		nlistf = *argv;
    262 		if (*++argv) {
    263 			memf = *argv;
    264 			if (*++argv)
    265 				swapf = *argv;
    266 		}
    267 	}
    268 #endif
    269 	/*
    270 	 * Discard setgid privileges.  If not the running kernel, we toss
    271 	 * them away totally so that bad guys can't print interesting stuff
    272 	 * from kernel memory, otherwise switch back to kmem for the
    273 	 * duration of the kvm_openfiles() call.
    274 	 */
    275 	if (nlistf != NULL || memf != NULL || swapf != NULL)
    276 		(void)setgid(getgid());
    277 	else
    278 		(void)setegid(egid);
    279 
    280 	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
    281 	if (kd == 0)
    282 		errx(1, "%s", errbuf);
    283 
    284 	if (nlistf == NULL && memf == NULL && swapf == NULL)
    285 		(void)setgid(getgid());
    286 
    287 	if (!fmt)
    288 		parsefmt(dfmt);
    289 
    290 	if (!all && ttydev == NODEV && pid == -1)  /* XXX - should be cleaner */
    291 		uid = getuid();
    292 
    293 	/*
    294 	 * scan requested variables, noting what structures are needed,
    295 	 * and adjusting header widths as appropiate.
    296 	 */
    297 	scanvars();
    298 	/*
    299 	 * get proc list
    300 	 */
    301 	if (uid != (uid_t) -1) {
    302 		what = KERN_PROC_UID;
    303 		flag = uid;
    304 	} else if (ttydev != NODEV) {
    305 		what = KERN_PROC_TTY;
    306 		flag = ttydev;
    307 	} else if (pid != -1) {
    308 		what = KERN_PROC_PID;
    309 		flag = pid;
    310 	} else {
    311 		what = KERN_PROC_ALL;
    312 		flag = 0;
    313 	}
    314 	/*
    315 	 * select procs
    316 	 */
    317 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
    318 		errx(1, "%s", kvm_geterr(kd));
    319 	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
    320 		err(1, "%s", "");
    321 	for (i = nentries; --i >= 0; ++kp) {
    322 		kinfo[i].ki_p = kp;
    323 		if (needuser)
    324 			saveuser(&kinfo[i]);
    325 	}
    326 	/*
    327 	 * print header
    328 	 */
    329 	printheader();
    330 	if (nentries == 0)
    331 		exit(0);
    332 	/*
    333 	 * sort proc list
    334 	 */
    335 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
    336 	/*
    337 	 * for each proc, call each variable output function.
    338 	 */
    339 	for (i = lineno = 0; i < nentries; i++) {
    340 		KINFO *ki = &kinfo[i];
    341 
    342 		if (xflg == 0 && (KI_EPROC(ki)->e_tdev == NODEV ||
    343 		    (KI_PROC(ki)->p_flag & P_CONTROLT ) == 0))
    344 			continue;
    345 		for (vent = vhead; vent; vent = vent->next) {
    346 			(vent->var->oproc)(ki, vent);
    347 			if (vent->next != NULL)
    348 				(void)putchar(' ');
    349 		}
    350 		(void)putchar('\n');
    351 		if (prtheader && lineno++ == prtheader - 4) {
    352 			(void)putchar('\n');
    353 			printheader();
    354 			lineno = 0;
    355 		}
    356 	}
    357 	exit(eval);
    358 }
    359 
    360 static void
    361 scanvars()
    362 {
    363 	struct varent *vent;
    364 	VAR *v;
    365 	int i;
    366 
    367 	for (vent = vhead; vent; vent = vent->next) {
    368 		v = vent->var;
    369 		i = strlen(v->header);
    370 		if (v->width < i)
    371 			v->width = i;
    372 		totwidth += v->width + 1;	/* +1 for space */
    373 		if (v->flag & USER)
    374 			needuser = 1;
    375 		if (v->flag & COMM)
    376 			needcomm = 1;
    377 	}
    378 	totwidth--;
    379 }
    380 
    381 static void
    382 saveuser(ki)
    383 	KINFO *ki;
    384 {
    385 	struct pstats pstats;
    386 	struct usave *usp;
    387 
    388 	usp = &ki->ki_u;
    389 	if (kvm_read(kd, (u_long)&KI_PROC(ki)->p_addr->u_stats,
    390 	    (char *)&pstats, sizeof(pstats)) == sizeof(pstats)) {
    391 		/*
    392 		 * The u-area might be swapped out, and we can't get
    393 		 * at it because we have a crashdump and no swap.
    394 		 * If it's here fill in these fields, otherwise, just
    395 		 * leave them 0.
    396 		 */
    397 		usp->u_start = pstats.p_start;
    398 		usp->u_ru = pstats.p_ru;
    399 		usp->u_cru = pstats.p_cru;
    400 		usp->u_valid = 1;
    401 	} else
    402 		usp->u_valid = 0;
    403 }
    404 
    405 static int
    406 pscomp(a, b)
    407 	const void *a, *b;
    408 {
    409 	int i;
    410 #ifdef NEWVM
    411 #define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
    412 		  KI_EPROC(k)->e_vm.vm_tsize)
    413 #else
    414 #define VSIZE(k) ((k)->ki_p->p_dsize + (k)->ki_p->p_ssize + (k)->ki_e->e_xsize)
    415 #endif
    416 
    417 	if (sortby == SORTCPU)
    418 		return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
    419 	if (sortby == SORTMEM)
    420 		return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
    421 	i =  KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
    422 	if (i == 0)
    423 		i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
    424 	return (i);
    425 }
    426 
    427 /*
    428  * ICK (all for getopt), would rather hide the ugliness
    429  * here than taint the main code.
    430  *
    431  *  ps foo -> ps -foo
    432  *  ps 34 -> ps -p34
    433  *
    434  * The old convention that 't' with no trailing tty arg means the users
    435  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
    436  * feature is available with the option 'T', which takes no argument.
    437  */
    438 static char *
    439 kludge_oldps_options(s)
    440 	char *s;
    441 {
    442 	size_t len;
    443 	char *newopts, *ns, *cp;
    444 
    445 	len = strlen(s);
    446 	if ((newopts = ns = malloc(len + 3)) == NULL)
    447 		err(1, "%s", "");
    448 	/*
    449 	 * options begin with '-'
    450 	 */
    451 	if (*s != '-')
    452 		*ns++ = '-';	/* add option flag */
    453 	/*
    454 	 * gaze to end of argv[1]
    455 	 */
    456 	cp = s + len - 1;
    457 	/*
    458 	 * if last letter is a 't' flag with no argument (in the context
    459 	 * of the oldps options -- option string NOT starting with a '-' --
    460 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
    461 	 */
    462 	if (*cp == 't' && *s != '-')
    463 		*cp = 'T';
    464 	else {
    465 		/*
    466 		 * otherwise check for trailing number, which *may* be a
    467 		 * pid.
    468 		 */
    469 		while (cp >= s && isdigit(*cp))
    470 			--cp;
    471 	}
    472 	cp++;
    473 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
    474 	ns += cp - s;
    475 	/*
    476 	 * if there's a trailing number, and not a preceding 'p' (pid) or
    477 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
    478 	 */
    479 	if (isdigit(*cp) && (cp == s || (cp[-1] != 't' && cp[-1] != 'p' &&
    480 	    (cp - 1 == s || cp[-2] != 't'))))
    481 		*ns++ = 'p';
    482 	/* and append the number */
    483 	(void)strcpy(ns, cp);		/* XXX strcpy is safe */
    484 
    485 	return (newopts);
    486 }
    487 
    488 static void
    489 usage()
    490 {
    491 
    492 	(void)fprintf(stderr,
    493 	    "usage:\t%s\n\t   %s\n\t%s\n",
    494 	    "ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
    495 	    "[-M core] [-N system] [-W swap]",
    496 	    "ps [-L]");
    497 	exit(1);
    498 }
    499