Home | History | Annotate | Line # | Download | only in ps
ps.c revision 1.96
      1 /*	$NetBSD: ps.c,v 1.96 2021/06/04 22:39:41 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2000-2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Simon Burge.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1990, 1993, 1994
     34  *	The Regents of the University of California.  All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. Neither the name of the University nor the names of its contributors
     45  *    may be used to endorse or promote products derived from this software
     46  *    without specific prior written permission.
     47  *
     48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     58  * SUCH DAMAGE.
     59  */
     60 
     61 #include <sys/cdefs.h>
     62 #ifndef lint
     63 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\
     64  The Regents of the University of California.  All rights reserved.");
     65 #endif /* not lint */
     66 
     67 #ifndef lint
     68 #if 0
     69 static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
     70 #else
     71 __RCSID("$NetBSD: ps.c,v 1.96 2021/06/04 22:39:41 christos Exp $");
     72 #endif
     73 #endif /* not lint */
     74 
     75 #include <sys/param.h>
     76 #include <sys/time.h>
     77 #include <sys/resource.h>
     78 #include <sys/lwp.h>
     79 #include <sys/proc.h>
     80 #include <sys/stat.h>
     81 #include <sys/ioctl.h>
     82 #include <sys/sysctl.h>
     83 
     84 #include <stddef.h>
     85 #include <ctype.h>
     86 #include <err.h>
     87 #include <errno.h>
     88 #include <fcntl.h>
     89 #include <grp.h>
     90 #include <kvm.h>
     91 #include <limits.h>
     92 #include <locale.h>
     93 #include <math.h>
     94 #include <nlist.h>
     95 #include <paths.h>
     96 #include <pwd.h>
     97 #include <stdio.h>
     98 #include <stdlib.h>
     99 #include <string.h>
    100 #include <unistd.h>
    101 
    102 #include "ps.h"
    103 
    104 /*
    105  * ARGOPTS must contain all option characters that take arguments
    106  * (except for 't'!) - it is used in kludge_oldps_options()
    107  */
    108 #define	GETOPTSTR	"aAcCdegG:hjk:LlM:mN:O:o:p:rSsTt:U:uvW:wx"
    109 #define	ARGOPTS		"GkMNOopUW"
    110 
    111 struct varlist displaylist = SIMPLEQ_HEAD_INITIALIZER(displaylist);
    112 struct varlist sortlist = SIMPLEQ_HEAD_INITIALIZER(sortlist);
    113 
    114 int	eval;			/* exit value */
    115 int	sumrusage;		/* -S */
    116 int	termwidth;		/* width of screen (0 == infinity) */
    117 int	totwidth;		/* calculated width of requested variables */
    118 
    119 int	needcomm, needenv, commandonly;
    120 uid_t	myuid;
    121 
    122 static struct kinfo_lwp
    123 		*pick_representative_lwp(struct kinfo_proc2 *,
    124 		    struct kinfo_lwp *, int);
    125 static struct kinfo_proc2
    126 		*getkinfo_kvm(kvm_t *, int, int, int *);
    127 static struct pinfo
    128 		*setpinfo(struct kinfo_proc2 *, int, int, int);
    129 static char	*kludge_oldps_options(char *);
    130 static int	 pscomp(const void *, const void *);
    131 static void	 scanvars(void);
    132 __dead static void	 usage(void);
    133 static int	 parsenum(const char *, const char *);
    134 static void	 descendant_sort(struct pinfo *, int);
    135 
    136 char dfmt[] = "pid tt state time command";
    137 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
    138 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
    139 char sfmt[] = "uid pid ppid cpu lid nlwp pri nice vsz rss wchan lstate tt "
    140 		"ltime command";
    141 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
    142 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
    143 
    144 const char *default_fmt = dfmt;
    145 
    146 struct varent *Opos = NULL; /* -O flag inserts after this point */
    147 
    148 kvm_t *kd;
    149 
    150 static long long
    151 ttyname2dev(const char *ttname, int *xflg, int *what)
    152 {
    153 	struct stat sb;
    154 	const char *ttypath;
    155 	char pathbuf[MAXPATHLEN];
    156 
    157 	ttypath = NULL;
    158 	if (strcmp(ttname, "?") == 0) {
    159 		*xflg = 1;
    160 		return KERN_PROC_TTY_NODEV;
    161 	}
    162 	if (strcmp(ttname, "-") == 0)
    163 		return KERN_PROC_TTY_REVOKE;
    164 
    165 	if (strcmp(ttname, "co") == 0)
    166 		ttypath = _PATH_CONSOLE;
    167 	else if (strncmp(ttname, "pts/", 4) == 0 ||
    168 		strncmp(ttname, "tty", 3) == 0) {
    169 		(void)snprintf(pathbuf,
    170 		    sizeof(pathbuf), "%s%s", _PATH_DEV, ttname);
    171 		ttypath = pathbuf;
    172 	} else if (*ttname != '/') {
    173 		(void)snprintf(pathbuf,
    174 		    sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
    175 		ttypath = pathbuf;
    176 	} else
    177 		ttypath = ttname;
    178 	*what = KERN_PROC_TTY;
    179 	if (stat(ttypath, &sb) == -1) {
    180 		devmajor_t pts;
    181 		int serrno;
    182 
    183 		serrno = errno;
    184 		pts = getdevmajor("pts", S_IFCHR);
    185 		if (pts != NODEVMAJOR && strncmp(ttname, "pts/", 4) == 0) {
    186 			int ptsminor = atoi(ttname + 4);
    187 
    188 			snprintf(pathbuf, sizeof(pathbuf), "pts/%d", ptsminor);
    189 			if (strcmp(pathbuf, ttname) == 0 && ptsminor >= 0)
    190 				return makedev(pts, ptsminor);
    191 		}
    192 		errno = serrno;
    193 		err(EXIT_FAILURE, "%s", ttypath);
    194 	}
    195 	if (!S_ISCHR(sb.st_mode))
    196 		errx(EXIT_FAILURE, "%s: not a terminal", ttypath);
    197 	return sb.st_rdev;
    198 }
    199 
    200 int
    201 main(int argc, char *argv[])
    202 {
    203 	struct kinfo_proc2 *kinfo;
    204 	struct pinfo *pinfo;
    205 	struct varent *vent;
    206 	struct winsize ws;
    207 	struct kinfo_lwp *kl, *l;
    208 	int ch, i, j, fmt, lineno, descendancy, nentries, nlwps;
    209 	long long flag;
    210 	int calc_pcpu, prtheader, wflag, what, xflg, rawcpu, showlwps;
    211 	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
    212 	char *ttname;
    213 
    214 	setprogname(argv[0]);
    215 	(void)setlocale(LC_ALL, "");
    216 
    217 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    218 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    219 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
    220 	     ws.ws_col == 0)
    221 		termwidth = 79;
    222 	else
    223 		termwidth = ws.ws_col - 1;
    224 
    225 	if (argc > 1)
    226 		argv[1] = kludge_oldps_options(argv[1]);
    227 
    228 	descendancy = fmt = prtheader = wflag = xflg = rawcpu = showlwps = 0;
    229 	what = KERN_PROC_UID;
    230 	flag = myuid = getuid();
    231 	memf = nlistf = swapf = NULL;
    232 
    233 	while ((ch = getopt(argc, argv, GETOPTSTR)) != -1)
    234 		switch((char)ch) {
    235 		case 'A':
    236 			/* "-A" shows all processes, like "-ax" */
    237 			xflg = 1;
    238 			/*FALLTHROUGH*/
    239 		case 'a':
    240 			what = KERN_PROC_ALL;
    241 			flag = 0;
    242 			break;
    243 		case 'c':
    244 			commandonly = 1;
    245 			break;
    246 		case 'd':
    247 			descendancy = 1;
    248 			break;
    249 		case 'e':			/* XXX set ufmt */
    250 			needenv = 1;
    251 			break;
    252 		case 'C':
    253 			rawcpu = 1;
    254 			break;
    255 		case 'g':
    256 			break;			/* no-op */
    257 		case 'G':
    258 			if (*optarg != '\0') {
    259 				struct group *gr;
    260 
    261 				what = KERN_PROC_GID;
    262 				gr = getgrnam(optarg);
    263 				if (gr == NULL) {
    264 					flag = parsenum(optarg, "group id");
    265 				} else
    266 					flag = gr->gr_gid;
    267 			}
    268 			break;
    269 
    270 		case 'h':
    271 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
    272 			break;
    273 		case 'j':
    274 			parsefmt(jfmt);
    275 			fmt = 1;
    276 			jfmt[0] = '\0';
    277 			break;
    278 		case 'k':
    279 			parsesort(optarg);
    280 			break;
    281 		case 'K':
    282 			break;			/* no-op - was dontuseprocfs */
    283 		case 'L':
    284 			showkey();
    285 			return 0;
    286 		case 'l':
    287 			parsefmt(lfmt);
    288 			fmt = 1;
    289 			lfmt[0] = '\0';
    290 			break;
    291 		case 'M':
    292 			memf = optarg;
    293 			break;
    294 		case 'm':
    295 			parsesort("vsz");
    296 			break;
    297 		case 'N':
    298 			nlistf = optarg;
    299 			break;
    300 		case 'O':
    301 			/*
    302 			 * If this is not the first -O option, insert
    303 			 * just after the previous one.
    304 			 *
    305 			 * If there is no format yet, start with the default
    306 			 * format, and insert after the pid column.
    307 			 *
    308 			 * If there is already a format, insert after
    309 			 * the pid column, or at the end if there's no
    310 			 * pid column.
    311 			 */
    312 			if (!Opos) {
    313 				if (!fmt)
    314 					parsefmt(default_fmt);
    315 				Opos = varlist_find(&displaylist, "pid");
    316 			}
    317 			parsefmt_insert(optarg, &Opos);
    318 			fmt = 1;
    319 			break;
    320 		case 'o':
    321 			parsefmt(optarg);
    322 			fmt = 1;
    323 			break;
    324 		case 'p':
    325 			what = KERN_PROC_PID;
    326 			flag = parsenum(optarg, "process id");
    327 			xflg = 1;
    328 			break;
    329 		case 'r':
    330 			parsesort("%cpu");
    331 			break;
    332 		case 'S':
    333 			sumrusage = 1;
    334 			break;
    335 		case 's':
    336 			/* -L was already taken... */
    337 			showlwps = 1;
    338 			default_fmt = sfmt;
    339 			break;
    340 		case 'T':
    341 			if ((ttname = ttyname(STDIN_FILENO)) == NULL)
    342 				errx(EXIT_FAILURE, "stdin: not a terminal");
    343 			flag = ttyname2dev(ttname, &xflg, &what);
    344 			break;
    345 		case 't':
    346 			flag = ttyname2dev(optarg, &xflg, &what);
    347 			break;
    348 		case 'U':
    349 			if (*optarg != '\0') {
    350 				struct passwd *pw;
    351 
    352 				what = KERN_PROC_UID;
    353 				pw = getpwnam(optarg);
    354 				if (pw == NULL) {
    355 					flag = parsenum(optarg, "user id");
    356 				} else
    357 					flag = pw->pw_uid;
    358 			}
    359 			break;
    360 		case 'u':
    361 			parsefmt(ufmt);
    362 			parsesort("%cpu");
    363 			fmt = 1;
    364 			ufmt[0] = '\0';
    365 			break;
    366 		case 'v':
    367 			parsefmt(vfmt);
    368 			parsesort("vsz");
    369 			fmt = 1;
    370 			vfmt[0] = '\0';
    371 			break;
    372 		case 'W':
    373 			swapf = optarg;
    374 			break;
    375 		case 'w':
    376 			if (wflag)
    377 				termwidth = UNLIMITED;
    378 			else if (termwidth < 131)
    379 				termwidth = 131;
    380 			wflag++;
    381 			break;
    382 		case 'x':
    383 			xflg = 1;
    384 			break;
    385 		case '?':
    386 		default:
    387 			usage();
    388 		}
    389 	argc -= optind;
    390 	argv += optind;
    391 
    392 #define	BACKWARD_COMPATIBILITY
    393 #ifdef	BACKWARD_COMPATIBILITY
    394 	if (*argv) {
    395 		nlistf = *argv;
    396 		if (*++argv) {
    397 			memf = *argv;
    398 			if (*++argv)
    399 				swapf = *argv;
    400 		}
    401 	}
    402 #endif
    403 
    404 	if (memf == NULL) {
    405 		kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
    406 		donlist_sysctl();
    407 	} else
    408 		kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
    409 
    410 	if (kd == NULL)
    411 		errx(EXIT_FAILURE, "%s", errbuf);
    412 
    413 	if (!fmt)
    414 		parsefmt(default_fmt);
    415 
    416 	/* Add default sort criteria */
    417 	parsesort("tdev,pid");
    418 	calc_pcpu = 0;
    419 	SIMPLEQ_FOREACH(vent, &sortlist, next) {
    420 		if (vent->var->flag & LWP || vent->var->type == UNSPECIFIED)
    421 			warnx("Cannot sort on %s, sort key ignored",
    422 				vent->var->name);
    423 		if (vent->var->type == PCPU)
    424 			calc_pcpu = 1;
    425 	}
    426 	if (!calc_pcpu)
    427 		SIMPLEQ_FOREACH(vent, &displaylist, next)
    428 			if (vent->var->type == PCPU) {
    429 				calc_pcpu = 1;
    430 				break;
    431 			}
    432 
    433 	/*
    434 	 * scan requested variables, noting what structures are needed.
    435 	 */
    436 	scanvars();
    437 
    438 	/*
    439 	 * select procs
    440 	 */
    441 	if (!(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
    442 		errx(EXIT_FAILURE, "%s", kvm_geterr(kd));
    443 	if (nentries == 0) {
    444 		printheader();
    445 		return 1;
    446 	}
    447 	pinfo = setpinfo(kinfo, nentries, calc_pcpu, rawcpu);
    448 
    449 	/*
    450 	 * sort proc list
    451 	 */
    452 	qsort(pinfo, nentries, sizeof(struct pinfo), pscomp);
    453 
    454 	/*
    455 	 * We want things in descendant order
    456 	 */
    457 	if (descendancy)
    458 		descendant_sort(pinfo, nentries);
    459 
    460 	/*
    461 	 * For each proc, call each variable output function in
    462 	 * "setwidth" mode to determine the widest element of
    463 	 * the column.
    464 	 */
    465 
    466 	for (i = 0; i < nentries; i++) {
    467 		struct pinfo *pi = &pinfo[i];
    468 		struct kinfo_proc2 *ki = pi->ki;
    469 
    470 		if (xflg == 0 && (ki->p_tdev == (uint32_t)NODEV ||
    471 		    (ki->p_flag & P_CONTROLT) == 0))
    472 			continue;
    473 
    474 		kl = kvm_getlwps(kd, ki->p_pid, ki->p_paddr,
    475 		    sizeof(struct kinfo_lwp), &nlwps);
    476 		if (kl == 0)
    477 			nlwps = 0;
    478 		if (showlwps == 0) {
    479 			l = pick_representative_lwp(ki, kl, nlwps);
    480 			SIMPLEQ_FOREACH(vent, &displaylist, next)
    481 				OUTPUT(vent, l, pi, ki, WIDTHMODE);
    482 		} else {
    483 			/* The printing is done with the loops
    484 			 * reversed, but here we don't need that,
    485 			 * and this improves the code locality a bit.
    486 			 */
    487 			SIMPLEQ_FOREACH(vent, &displaylist, next)
    488 				for (j = 0; j < nlwps; j++)
    489 					OUTPUT(vent, &kl[j], pi, ki, WIDTHMODE);
    490 		}
    491 	}
    492 	/*
    493 	 * Print header - AFTER determining process field widths.
    494 	 * printheader() also adds up the total width of all
    495 	 * fields the first time it's called.
    496 	 */
    497 	printheader();
    498 	/*
    499 	 * For each proc, call each variable output function in
    500 	 * print mode.
    501 	 */
    502 	for (i = lineno = 0; i < nentries; i++) {
    503 		struct pinfo *pi = &pinfo[i];
    504 		struct kinfo_proc2 *ki = pi->ki;
    505 
    506 		if (xflg == 0 && (ki->p_tdev == (uint32_t)NODEV ||
    507 		    (ki->p_flag & P_CONTROLT ) == 0))
    508 			continue;
    509 		kl = kvm_getlwps(kd, ki->p_pid, (u_long)ki->p_paddr,
    510 		    sizeof(struct kinfo_lwp), &nlwps);
    511 		if (kl == 0)
    512 			nlwps = 0;
    513 		if (showlwps == 0) {
    514 			l = pick_representative_lwp(ki, kl, nlwps);
    515 			SIMPLEQ_FOREACH(vent, &displaylist, next) {
    516 				OUTPUT(vent, l, pi, ki, PRINTMODE);
    517 				if (SIMPLEQ_NEXT(vent, next) != NULL)
    518 					(void)putchar(' ');
    519 			}
    520 			(void)putchar('\n');
    521 			if (prtheader && lineno++ == prtheader - 4) {
    522 				(void)putchar('\n');
    523 				printheader();
    524 				lineno = 0;
    525 			}
    526 		} else {
    527 			for (j = 0; j < nlwps; j++) {
    528 				SIMPLEQ_FOREACH(vent, &displaylist, next) {
    529 					OUTPUT(vent, &kl[j], pi, ki, PRINTMODE);
    530 					if (SIMPLEQ_NEXT(vent, next) != NULL)
    531 						(void)putchar(' ');
    532 				}
    533 				(void)putchar('\n');
    534 				if (prtheader && lineno++ == prtheader - 4) {
    535 					(void)putchar('\n');
    536 					printheader();
    537 					lineno = 0;
    538 				}
    539 			}
    540 		}
    541 	}
    542 
    543 #ifdef __NO_LEAKS
    544 	free(pinfo);
    545 #endif
    546 
    547 	return eval;
    548 }
    549 
    550 static struct kinfo_lwp *
    551 pick_representative_lwp(struct kinfo_proc2 *ki, struct kinfo_lwp *kl, int nlwps)
    552 {
    553 	int i, onproc, running, sleeping, stopped, suspended;
    554 	static struct kinfo_lwp zero_lwp;
    555 
    556 	if (kl == 0)
    557 		return &zero_lwp;
    558 
    559 	/* Trivial case: only one LWP */
    560 	if (nlwps == 1)
    561 		return kl;
    562 
    563 	switch (ki->p_realstat) {
    564 	case SSTOP:
    565 	case SACTIVE:
    566 		/* Pick the most live LWP */
    567 		onproc = running = sleeping = stopped = suspended = -1;
    568 		for (i = 0; i < nlwps; i++) {
    569 			switch (kl[i].l_stat) {
    570 			case LSONPROC:
    571 				onproc = i;
    572 				break;
    573 			case LSRUN:
    574 				running = i;
    575 				break;
    576 			case LSSLEEP:
    577 				sleeping = i;
    578 				break;
    579 			case LSSTOP:
    580 				stopped = i;
    581 				break;
    582 			case LSSUSPENDED:
    583 				suspended = i;
    584 				break;
    585 			}
    586 		}
    587 		if (onproc != -1)
    588 			return &kl[onproc];
    589 		if (running != -1)
    590 			return &kl[running];
    591 		if (sleeping != -1)
    592 			return &kl[sleeping];
    593 		if (stopped != -1)
    594 			return &kl[stopped];
    595 		if (suspended != -1)
    596 			return &kl[suspended];
    597 		break;
    598 	case SZOMB:
    599 		/* First will do */
    600 		return kl;
    601 		break;
    602 	}
    603 	/* Error condition! */
    604 	warnx("Inconsistent LWP state for process %d", ki->p_pid);
    605 	return kl;
    606 }
    607 
    608 static struct kinfo_proc2 *
    609 getkinfo_kvm(kvm_t *kdp, int what, int flag, int *nentriesp)
    610 {
    611 
    612 	return (kvm_getproc2(kdp, what, flag, sizeof(struct kinfo_proc2),
    613 	    nentriesp));
    614 }
    615 
    616 static struct pinfo *
    617 setpinfo(struct kinfo_proc2 *ki, int nentries, int calc_pcpu, int rawcpu)
    618 {
    619 	struct pinfo *pi;
    620 	int i;
    621 
    622 	pi = calloc(nentries, sizeof(*pi));
    623 	if (pi == NULL)
    624 		err(EXIT_FAILURE, "calloc");
    625 
    626 	if (calc_pcpu && !nlistread)
    627 		donlist();
    628 
    629 	for (i = 0; i < nentries; i++) {
    630 		pi[i].ki = &ki[i];
    631 		if (!calc_pcpu)
    632 			continue;
    633 		if (ki[i].p_swtime == 0 || ki[i].p_realstat == SZOMB) {
    634 			pi[i].pcpu = 0.0;
    635 			continue;
    636 		}
    637 		pi[i].pcpu = 100.0 * (double)ki[i].p_pctcpu / fscale;
    638 		if (!rawcpu)
    639 			pi[i].pcpu /= 1.0 - exp(ki[i].p_swtime * log_ccpu);
    640 	}
    641 
    642 	return pi;
    643 }
    644 
    645 static void
    646 scanvars(void)
    647 {
    648 	struct varent *vent;
    649 	VAR *v;
    650 
    651 	SIMPLEQ_FOREACH(vent, &displaylist, next) {
    652 		v = vent->var;
    653 		if (v->flag & COMM) {
    654 			needcomm = 1;
    655 			break;
    656 		}
    657 	}
    658 }
    659 
    660 static int
    661 pscomp(const void *a, const void *b)
    662 {
    663 	const struct pinfo *pa = (const struct pinfo *)a;
    664 	const struct pinfo *pb = (const struct pinfo *)b;
    665 	const struct kinfo_proc2 *ka = pa->ki;
    666 	const struct kinfo_proc2 *kb = pb->ki;
    667 
    668 	int i;
    669 	int64_t i64;
    670 	VAR *v;
    671 	struct varent *ve;
    672 	const sigset_t *sa, *sb;
    673 
    674 #define	V_SIZE(k) ((k)->p_vm_msize)
    675 #define	RDIFF_N(t, n) \
    676 	if (((const t *)((const char *)ka + v->off))[n] > ((const t *)((const char *)kb + v->off))[n]) \
    677 		return 1; \
    678 	if (((const t *)((const char *)ka + v->off))[n] < ((const t *)((const char *)kb + v->off))[n]) \
    679 		return -1;
    680 
    681 #define	RDIFF(type) RDIFF_N(type, 0); continue
    682 
    683 	SIMPLEQ_FOREACH(ve, &sortlist, next) {
    684 		v = ve->var;
    685 		if (v->flag & LWP)
    686 			/* LWP structure not available (yet) */
    687 			continue;
    688 		/* Sort on pvar() fields, + a few others */
    689 		switch (v->type) {
    690 		case CHAR:
    691 			RDIFF(char);
    692 		case UCHAR:
    693 			RDIFF(u_char);
    694 		case SHORT:
    695 			RDIFF(short);
    696 		case USHORT:
    697 			RDIFF(ushort);
    698 		case INT:
    699 			RDIFF(int);
    700 		case UINT:
    701 			RDIFF(uint);
    702 		case LONG:
    703 			RDIFF(long);
    704 		case ULONG:
    705 			RDIFF(ulong);
    706 		case INT32:
    707 			RDIFF(int32_t);
    708 		case UINT32:
    709 			RDIFF(uint32_t);
    710 		case SIGLIST:
    711 			sa = (const void *)((const char *)ka + v->off);
    712 			sb = (const void *)((const char *)kb + v->off);
    713 			i = 0;
    714 			do {
    715 				if (sa->__bits[i] > sb->__bits[i])
    716 					return 1;
    717 				if (sa->__bits[i] < sb->__bits[i])
    718 					return -1;
    719 				i++;
    720 			} while (i < (int)__arraycount(sa->__bits));
    721 			continue;
    722 		case INT64:
    723 			RDIFF(int64_t);
    724 		case KPTR:
    725 		case KPTR24:
    726 		case UINT64:
    727 			RDIFF(uint64_t);
    728 		case TIMEVAL:
    729 			/* compare xxx_sec then xxx_usec */
    730 			RDIFF_N(uint32_t, 0);
    731 			RDIFF_N(uint32_t, 1);
    732 			continue;
    733 		case CPUTIME:
    734 			i64 = ka->p_rtime_sec * 1000000 + ka->p_rtime_usec;
    735 			i64 -= kb->p_rtime_sec * 1000000 + kb->p_rtime_usec;
    736 			if (sumrusage) {
    737 				i64 += ka->p_uctime_sec * 1000000
    738 				    + ka->p_uctime_usec;
    739 				i64 -= kb->p_uctime_sec * 1000000
    740 				    + kb->p_uctime_usec;
    741 			}
    742 			if (i64 != 0)
    743 				return i64 > 0 ? 1 : -1;
    744 			continue;
    745 		case PCPU:
    746 			i = pb->pcpu - pa->pcpu;
    747 			if (i != 0)
    748 				return i;
    749 			continue;
    750 		case VSIZE:
    751 			i = V_SIZE(kb) - V_SIZE(ka);
    752 			if (i != 0)
    753 				return i;
    754 			continue;
    755 
    756 		default:
    757 			/* Ignore everything else */
    758 			break;
    759 		}
    760 	}
    761 	return 0;
    762 
    763 #undef VSIZE
    764 }
    765 
    766 /*
    767  * ICK (all for getopt), would rather hide the ugliness
    768  * here than taint the main code.
    769  *
    770  *  ps foo -> ps -foo
    771  *  ps 34 -> ps -p34
    772  *
    773  * The old convention that 't' with no trailing tty arg means the user's
    774  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
    775  * feature is available with the option 'T', which takes no argument.
    776  */
    777 static char *
    778 kludge_oldps_options(char *s)
    779 {
    780 	size_t len;
    781 	char *newopts, *ns, *cp;
    782 
    783 	len = strlen(s);
    784 	if ((newopts = ns = malloc(len + 3)) == NULL)
    785 		err(EXIT_FAILURE, NULL);
    786 	/*
    787 	 * options begin with '-'
    788 	 */
    789 	if (*s != '-')
    790 		*ns++ = '-';	/* add option flag */
    791 	/*
    792 	 * gaze to end of argv[1]
    793 	 */
    794 	cp = s + len - 1;
    795 	/*
    796 	 * if the last letter is a 't' flag and there are no other option
    797 	 * characters that take arguments (eg U, p, o) in the option
    798 	 * string and the option string doesn't start with a '-' then
    799 	 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
    800 	 */
    801 	if (*cp == 't' && *s != '-' && strpbrk(s, ARGOPTS) == NULL)
    802 		*cp = 'T';
    803 	else {
    804 		/*
    805 		 * otherwise check for trailing number, which *may* be a
    806 		 * pid.
    807 		 */
    808 		while (cp >= s && isdigit((unsigned char)*cp))
    809 			--cp;
    810 	}
    811 	cp++;
    812 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
    813 	ns += cp - s;
    814 	/*
    815 	 * if there's a trailing number, and not a preceding 'p' (pid) or
    816 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
    817 	 */
    818 	if (isdigit((unsigned char)*cp) &&
    819 	    (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
    820 	    cp[-1] != '/' && (cp - 1 == s || cp[-2] != 't'))))
    821 		*ns++ = 'p';
    822 	/* and append the number */
    823 	(void)strcpy(ns, cp);		/* XXX strcpy is safe here */
    824 
    825 	return (newopts);
    826 }
    827 
    828 static int
    829 parsenum(const char *str, const char *msg)
    830 {
    831 	char *ep;
    832 	unsigned long ul;
    833 
    834 	ul = strtoul(str, &ep, 0);
    835 
    836 	if (*str == '\0' || *ep != '\0')
    837 		errx(EXIT_FAILURE, "Invalid %s: `%s'", msg, str);
    838 
    839 	if (ul > INT_MAX)
    840 		errx(EXIT_FAILURE, "Out of range %s: `%s'", msg, str);
    841 
    842 	return (int)ul;
    843 }
    844 
    845 static void
    846 descendant_sort(struct pinfo *ki, int items)
    847 {
    848 	int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
    849 	unsigned char *path;
    850 	struct pinfo kn;
    851 
    852 	/*
    853 	 * First, sort the entries by descendancy, tracking the descendancy
    854 	 * depth in the level field.
    855 	 */
    856 	src = 0;
    857 	maxlvl = 0;
    858 	while (src < items) {
    859 		if (ki[src].level) {
    860 			src++;
    861 			continue;
    862 		}
    863 		for (nsrc = 1; src + nsrc < items; nsrc++)
    864 			if (!ki[src + nsrc].level)
    865 				break;
    866 
    867 		for (dst = 0; dst < items; dst++) {
    868 			if (ki[dst].ki->p_pid == ki[src].ki->p_pid)
    869 				continue;
    870 			if (ki[dst].ki->p_pid == ki[src].ki->p_ppid)
    871 				break;
    872 		}
    873 
    874 		if (dst == items) {
    875 			src += nsrc;
    876 			continue;
    877 		}
    878 
    879 		for (ndst = 1; dst + ndst < items; ndst++)
    880 			if (ki[dst + ndst].level <= ki[dst].level)
    881 				break;
    882 
    883 		for (n = src; n < src + nsrc; n++) {
    884 			ki[n].level += ki[dst].level + 1;
    885 			if (maxlvl < ki[n].level)
    886 				maxlvl = ki[n].level;
    887 		}
    888 
    889 		while (nsrc) {
    890 			if (src < dst) {
    891 				kn = ki[src];
    892 				memmove(ki + src, ki + src + 1,
    893 				    (dst - src + ndst - 1) * sizeof *ki);
    894 				ki[dst + ndst - 1] = kn;
    895 				nsrc--;
    896 				dst--;
    897 				ndst++;
    898 			} else if (src != dst + ndst) {
    899 				kn = ki[src];
    900 				memmove(ki + dst + ndst + 1, ki + dst + ndst,
    901 				    (src - dst - ndst) * sizeof *ki);
    902 				ki[dst + ndst] = kn;
    903 				ndst++;
    904 				nsrc--;
    905 				src++;
    906 			} else {
    907 				ndst += nsrc;
    908 				src += nsrc;
    909 				nsrc = 0;
    910 			}
    911 		}
    912 	}
    913 
    914 	/*
    915 	 * Now populate prefix (instead of level) with the command
    916 	 * prefix used to show descendancies.
    917 	 */
    918 	path = malloc((maxlvl + 7) / 8);
    919 	memset(path, '\0', (maxlvl + 7) / 8);
    920 	for (src = 0; src < items; src++) {
    921 		if ((lvl = ki[src].level) == 0) {
    922 			ki[src].prefix = NULL;
    923 			continue;
    924 		}
    925 		if ((ki[src].prefix = malloc(lvl * 2 + 1)) == NULL)
    926 			errx(EXIT_FAILURE, "malloc failed");
    927 		for (n = 0; n < lvl - 2; n++) {
    928 			ki[src].prefix[n * 2] =
    929 			    path[n / 8] & 1 << (n % 8) ? '|' : ' ';
    930 			ki[src].prefix[n * 2 + 1] = ' ';
    931 
    932 		}
    933 		if (n == lvl - 2) {
    934 			/* Have I any more siblings? */
    935 			for (siblings = 0, dst = src + 1; dst < items; dst++) {
    936 				if (ki[dst].level > lvl)
    937 					continue;
    938 				if (ki[dst].level == lvl)
    939 					siblings = 1;
    940 				break;
    941 			}
    942 			if (siblings)
    943 				path[n / 8] |= 1 << (n % 8);
    944 			else
    945 				path[n / 8] &= ~(1 << (n % 8));
    946 			ki[src].prefix[n * 2] = siblings ? '|' : '`';
    947 			ki[src].prefix[n * 2 + 1] = '-';
    948 			n++;
    949 		}
    950 		strcpy(ki[src].prefix + n * 2, "- ");
    951 	}
    952 	free(path);
    953 }
    954 
    955 static void
    956 usage(void)
    957 {
    958 
    959 	(void)fprintf(stderr,
    960 	    "usage:\t%s\n\t   %s\n\t%s\n",
    961 	    "ps [-AaCcdehjlmrSsTuvwx] [-G group] [-k key] [-M core] [-N system]",
    962 	    "[-O fmt] [-o fmt] [-p pid] [-t tty] [-U user] [-W swap]",
    963 	    "ps -L");
    964 	exit(1);
    965 	/* NOTREACHED */
    966 }
    967