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