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