Home | History | Annotate | Line # | Download | only in ps
ps.c revision 1.37
      1 /*	$NetBSD: ps.c,v 1.37 2000/04/29 00:18:48 abs 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.37 2000/04/29 00:18:48 abs 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 <pwd.h>
     68 #include <stdio.h>
     69 #include <stdlib.h>
     70 #include <string.h>
     71 #include <unistd.h>
     72 
     73 #include "ps.h"
     74 
     75 #ifdef P_PPWAIT
     76 #define NEWVM
     77 #endif
     78 
     79 KINFO *kinfo;
     80 struct varent *vhead, *vtail;
     81 
     82 int	eval;			/* exit value */
     83 int	rawcpu;			/* -C */
     84 int	sumrusage;		/* -S */
     85 int	dontuseprocfs=0;	/* -K */
     86 int	termwidth;		/* width of screen (0 == infinity) */
     87 int	totwidth;		/* calculated width of requested variables */
     88 
     89 int	needuser, needcomm, needenv, commandonly, use_procfs;
     90 uid_t	myuid;
     91 
     92 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
     93 
     94 static KINFO	*getkinfo_kvm __P((kvm_t *, int, int, int *, int));
     95 static char	*kludge_oldps_options __P((char *));
     96 static int	 pscomp __P((const void *, const void *));
     97 static void	 saveuser __P((KINFO *));
     98 static void	 scanvars __P((void));
     99 static void	 usage __P((void));
    100 int		 main __P((int, char *[]));
    101 
    102 char dfmt[] = "pid tt state time command";
    103 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
    104 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
    105 char   o1[] = "pid";
    106 char   o2[] = "tt state time command";
    107 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
    108 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
    109 
    110 kvm_t *kd;
    111 
    112 int
    113 main(argc, argv)
    114 	int argc;
    115 	char *argv[];
    116 {
    117 	struct varent *vent;
    118 	struct winsize ws;
    119 	gid_t egid = getegid();
    120 	int ch, flag, i, fmt, lineno, nentries;
    121 	int prtheader, wflag, what, xflg;
    122 	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
    123 	char *ttname;
    124 
    125 	(void)setegid(getgid());
    126 	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 ||
    127 	     ws.ws_col == 0)
    128 		termwidth = 79;
    129 	else
    130 		termwidth = ws.ws_col - 1;
    131 
    132 	if (argc > 1)
    133 		argv[1] = kludge_oldps_options(argv[1]);
    134 
    135 	fmt = prtheader = wflag = xflg = 0;
    136 	what = KERN_PROC_UID;
    137 	flag = myuid = getuid();
    138 	memf = nlistf = swapf = NULL;
    139 	while ((ch = getopt(argc, argv,
    140 	    "acCeghjKLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
    141 		switch((char)ch) {
    142 		case 'a':
    143 			what = KERN_PROC_ALL;
    144 			flag = 0;
    145 			break;
    146 		case 'c':
    147 			commandonly = 1;
    148 			break;
    149 		case 'e':			/* XXX set ufmt */
    150 			needenv = 1;
    151 			break;
    152 		case 'C':
    153 			rawcpu = 1;
    154 			break;
    155 		case 'g':
    156 			break;			/* no-op */
    157 		case 'h':
    158 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
    159 			break;
    160 		case 'j':
    161 			parsefmt(jfmt);
    162 			fmt = 1;
    163 			jfmt[0] = '\0';
    164 			break;
    165 		case 'K':
    166 			dontuseprocfs=1;
    167 			break;
    168 		case 'L':
    169 			showkey();
    170 			exit(0);
    171 			/* NOTREACHED */
    172 		case 'l':
    173 			parsefmt(lfmt);
    174 			fmt = 1;
    175 			lfmt[0] = '\0';
    176 			break;
    177 		case 'M':
    178 			memf = optarg;
    179 			dontuseprocfs = 1;
    180 			break;
    181 		case 'm':
    182 			sortby = SORTMEM;
    183 			break;
    184 		case 'N':
    185 			nlistf = optarg;
    186 			break;
    187 		case 'O':
    188 			parsefmt(o1);
    189 			parsefmt(optarg);
    190 			parsefmt(o2);
    191 			o1[0] = o2[0] = '\0';
    192 			fmt = 1;
    193 			break;
    194 		case 'o':
    195 			parsefmt(optarg);
    196 			fmt = 1;
    197 			break;
    198 		case 'p':
    199 			what = KERN_PROC_PID;
    200 			flag = atol(optarg);
    201 			xflg = 1;
    202 			break;
    203 		case 'r':
    204 			sortby = SORTCPU;
    205 			break;
    206 		case 'S':
    207 			sumrusage = 1;
    208 			break;
    209 		case 'T':
    210 			if ((ttname = ttyname(STDIN_FILENO)) == NULL)
    211 				errx(1, "stdin: not a terminal");
    212 			goto tty;
    213 		case 't':
    214 			ttname = optarg;
    215 		tty: {
    216 			struct stat sb;
    217 			char *ttypath, pathbuf[MAXPATHLEN];
    218 
    219 			flag = 0;
    220 			if (strcmp(ttname, "?") == 0)
    221 				flag = KERN_PROC_TTY_NODEV;
    222 			else if (strcmp(ttname, "-") == 0)
    223 				flag = KERN_PROC_TTY_REVOKE;
    224 			else if (strcmp(ttname, "co") == 0)
    225 				ttypath = _PATH_CONSOLE;
    226 			else if (*ttname != '/')
    227 				(void)snprintf(ttypath = pathbuf,
    228 				    sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
    229 			else
    230 				ttypath = ttname;
    231 			what = KERN_PROC_TTY;
    232 			if (flag == 0) {
    233 				if (stat(ttypath, &sb) == -1)
    234 					err(1, "%s", ttypath);
    235 				if (!S_ISCHR(sb.st_mode))
    236 					errx(1, "%s: not a terminal", ttypath);
    237 				flag = sb.st_rdev;
    238 			}
    239 			break;
    240 		}
    241 		case 'U':
    242 			if (*optarg != '\0') {
    243 				struct passwd *pw;
    244 				char *ep;
    245 
    246 				what = KERN_PROC_UID;
    247 				pw = getpwnam(optarg);
    248 				if (pw == NULL) {
    249 					errno = 0;
    250 					flag = strtoul(optarg, &ep, 10);
    251 					if (errno)
    252 						err(1, "%s", optarg);
    253 					if (*ep != '\0')
    254 						errx(1, "%s: illegal user name",
    255 						    optarg);
    256 				} else
    257 					flag = pw->pw_uid;
    258 			}
    259 			break;
    260 		case 'u':
    261 			parsefmt(ufmt);
    262 			sortby = SORTCPU;
    263 			fmt = 1;
    264 			ufmt[0] = '\0';
    265 			break;
    266 		case 'v':
    267 			parsefmt(vfmt);
    268 			sortby = SORTMEM;
    269 			fmt = 1;
    270 			vfmt[0] = '\0';
    271 			break;
    272 		case 'W':
    273 			swapf = optarg;
    274 			break;
    275 		case 'w':
    276 			if (wflag)
    277 				termwidth = UNLIMITED;
    278 			else if (termwidth < 131)
    279 				termwidth = 131;
    280 			wflag++;
    281 			break;
    282 		case 'x':
    283 			xflg = 1;
    284 			break;
    285 		case '?':
    286 		default:
    287 			usage();
    288 		}
    289 	argc -= optind;
    290 	argv += optind;
    291 
    292 #define	BACKWARD_COMPATIBILITY
    293 #ifdef	BACKWARD_COMPATIBILITY
    294 	if (*argv) {
    295 		nlistf = *argv;
    296 		if (*++argv) {
    297 			memf = *argv;
    298 			if (*++argv)
    299 				swapf = *argv;
    300 		}
    301 	}
    302 #endif
    303 	/*
    304 	 * Discard setgid privileges.  If not the running kernel, we toss
    305 	 * them away totally so that bad guys can't print interesting stuff
    306 	 * from kernel memory, otherwise switch back to kmem for the
    307 	 * duration of the kvm_openfiles() call.
    308 	 */
    309 	if (nlistf != NULL || memf != NULL || swapf != NULL)
    310 		(void)setgid(getgid());
    311 	else
    312 		(void)setegid(egid);
    313 
    314 	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
    315 	if (kd == 0) {
    316 		if (dontuseprocfs)
    317 			errx(1, "%s", errbuf);
    318 		else {
    319 			warnx("kvm_openfiles: %s", errbuf);
    320 			fprintf(stderr, "ps: falling back to /proc-based lookup\n");
    321 		}
    322 	}
    323 
    324 	if (nlistf == NULL && memf == NULL && swapf == NULL)
    325 		(void)setgid(getgid());
    326 
    327 	if (!fmt)
    328 		parsefmt(dfmt);
    329 
    330 	/*
    331 	 * scan requested variables, noting what structures are needed,
    332 	 * and adjusting header widths as appropiate.
    333 	 */
    334 	scanvars();
    335 
    336 	/*
    337 	 * select procs
    338 	 */
    339 	if (!kd || !(kinfo = getkinfo_kvm(kd, what, flag, &nentries, needuser)))
    340 	{
    341 		/*  If/when the /proc-based code is ripped out
    342 		 *  again, make sure all references to the -K
    343 		 *  option are also pulled (getopt(), usage(),
    344 		 *  man page).  See the man page comments about
    345 		 *  this for more details.  */
    346 	  	/*  sysctl() ought to provide some sort of
    347 		 *  always-working-but-minimal-functionality
    348 		 *  method of providing at least some of the
    349 		 *  process information.  Unfortunately, such a
    350 		 *  change will require too much work to be put
    351 		 *  into 1.4.  For now, enable this experimental
    352 		 *  /proc-based support instead (if /proc is
    353 		 *  mounted) to grab as much information as we can.
    354 		 *  The guts of emulating kvm_getprocs() is in
    355 		 *  the file procfs_ops.c.  */
    356 		if (kd)
    357 			warnx("%s.", kvm_geterr(kd));
    358 		if (dontuseprocfs) {
    359 			exit(1);
    360 		}
    361 		/*  procfs_getprocs supports all but the
    362 		 *  KERN_PROC_RUID flag.  */
    363 		kinfo = getkinfo_procfs(what, flag, &nentries);
    364 		if (kinfo == 0) {
    365 		  errx(1, "fallback /proc-based lookup also failed.  %s",
    366 				  "Giving up...");
    367 		}
    368 		fprintf(stderr, "%s%s",
    369 		    "Warning:  /proc does not provide ",
    370 		    "valid data for all fields.\n");
    371 		use_procfs = 1;
    372 	}
    373 
    374 	/*
    375 	 * print header
    376 	 */
    377 	printheader();
    378 	if (nentries == 0)
    379 		exit(0);
    380 	/*
    381 	 * sort proc list
    382 	 */
    383 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
    384 	/*
    385 	 * for each proc, call each variable output function.
    386 	 */
    387 	for (i = lineno = 0; i < nentries; i++) {
    388 		KINFO *ki = &kinfo[i];
    389 
    390 		if (xflg == 0 && (KI_EPROC(ki)->e_tdev == NODEV ||
    391 		    (KI_PROC(ki)->p_flag & P_CONTROLT ) == 0))
    392 			continue;
    393 		for (vent = vhead; vent; vent = vent->next) {
    394 			(vent->var->oproc)(ki, vent);
    395 			if (vent->next != NULL)
    396 				(void)putchar(' ');
    397 		}
    398 		(void)putchar('\n');
    399 		if (prtheader && lineno++ == prtheader - 4) {
    400 			(void)putchar('\n');
    401 			printheader();
    402 			lineno = 0;
    403 		}
    404 	}
    405 	exit(eval);
    406 	/* NOTREACHED */
    407 }
    408 
    409 static KINFO *
    410 getkinfo_kvm(kd, what, flag, nentriesp, needuser)
    411 	kvm_t *kd;
    412 	int what, flag, *nentriesp, needuser;
    413 {
    414 	struct kinfo_proc *kp;
    415 	KINFO *kinfo=NULL;
    416 	size_t i;
    417 
    418 	if ((kp = kvm_getprocs(kd, what, flag, nentriesp)) != 0)
    419 	{
    420 		if ((kinfo = malloc((*nentriesp) * sizeof(*kinfo))) == NULL)
    421 			err(1, NULL);
    422 		for (i = (*nentriesp); i-- > 0; kp++) {
    423 			kinfo[i].ki_p = kp;
    424 			if (needuser)
    425 				saveuser(&kinfo[i]);
    426 		}
    427 	}
    428 
    429 	return (kinfo);
    430 }
    431 
    432 static void
    433 scanvars()
    434 {
    435 	struct varent *vent;
    436 	VAR *v;
    437 	int i;
    438 
    439 	for (vent = vhead; vent; vent = vent->next) {
    440 		v = vent->var;
    441 		i = strlen(v->header);
    442 		if (v->width < i)
    443 			v->width = i;
    444 		totwidth += v->width + 1;	/* +1 for space */
    445 		if (v->flag & USER)
    446 			needuser = 1;
    447 		if (v->flag & COMM)
    448 			needcomm = 1;
    449 	}
    450 	totwidth--;
    451 }
    452 
    453 static void
    454 saveuser(ki)
    455 	KINFO *ki;
    456 {
    457 	struct pstats pstats;
    458 	struct usave *usp;
    459 
    460 	usp = &ki->ki_u;
    461 	if (kvm_read(kd, (u_long)&KI_PROC(ki)->p_addr->u_stats,
    462 	    (char *)&pstats, sizeof(pstats)) == sizeof(pstats)) {
    463 		/*
    464 		 * The u-area might be swapped out, and we can't get
    465 		 * at it because we have a crashdump and no swap.
    466 		 * If it's here fill in these fields, otherwise, just
    467 		 * leave them 0.
    468 		 */
    469 		usp->u_start = pstats.p_start;
    470 		usp->u_ru = pstats.p_ru;
    471 		usp->u_cru = pstats.p_cru;
    472 		usp->u_valid = 1;
    473 	} else
    474 		usp->u_valid = 0;
    475 }
    476 
    477 static int
    478 pscomp(a, b)
    479 	const void *a, *b;
    480 {
    481 	int i;
    482 #ifdef NEWVM
    483 #define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
    484 		  KI_EPROC(k)->e_vm.vm_tsize)
    485 #else
    486 #define VSIZE(k) ((k)->ki_p->p_dsize + (k)->ki_p->p_ssize + (k)->ki_e->e_xsize)
    487 #endif
    488 
    489 	if (sortby == SORTCPU)
    490 		return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
    491 	if (sortby == SORTMEM)
    492 		return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
    493 	i =  KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
    494 	if (i == 0)
    495 		i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
    496 	return (i);
    497 }
    498 
    499 /*
    500  * ICK (all for getopt), would rather hide the ugliness
    501  * here than taint the main code.
    502  *
    503  *  ps foo -> ps -foo
    504  *  ps 34 -> ps -p34
    505  *
    506  * The old convention that 't' with no trailing tty arg means the user's
    507  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
    508  * feature is available with the option 'T', which takes no argument.
    509  */
    510 static char *
    511 kludge_oldps_options(s)
    512 	char *s;
    513 {
    514 	size_t len;
    515 	char *newopts, *ns, *cp;
    516 
    517 	len = strlen(s);
    518 	if ((newopts = ns = malloc(len + 3)) == NULL)
    519 		err(1, NULL);
    520 	/*
    521 	 * options begin with '-'
    522 	 */
    523 	if (*s != '-')
    524 		*ns++ = '-';	/* add option flag */
    525 	/*
    526 	 * gaze to end of argv[1]
    527 	 */
    528 	cp = s + len - 1;
    529 	/*
    530 	 * if last letter is a 't' flag with no argument (in the context
    531 	 * of the oldps options -- option string NOT starting with a '-' --
    532 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
    533 	 */
    534 	if (*cp == 't' && *s != '-')
    535 		*cp = 'T';
    536 	else {
    537 		/*
    538 		 * otherwise check for trailing number, which *may* be a
    539 		 * pid.
    540 		 */
    541 		while (cp >= s && isdigit(*cp))
    542 			--cp;
    543 	}
    544 	cp++;
    545 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
    546 	ns += cp - s;
    547 	/*
    548 	 * if there's a trailing number, and not a preceding 'p' (pid) or
    549 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
    550 	 */
    551 	if (isdigit(*cp) &&
    552 	    (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
    553 	     (cp - 1 == s || cp[-2] != 't'))))
    554 		*ns++ = 'p';
    555 	/* and append the number */
    556 	(void)strcpy(ns, cp);		/* XXX strcpy is safe */
    557 
    558 	return (newopts);
    559 }
    560 
    561 static void
    562 usage()
    563 {
    564 
    565 	(void)fprintf(stderr,
    566 	    "usage:\t%s\n\t   %s\n\t%s\n",
    567 	    "ps [-aChjKlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
    568 	    "[-M core] [-N system] [-W swap] [-U username]",
    569 	    "ps [-L]");
    570 	exit(1);
    571 	/* NOTREACHED */
    572 }
    573