Home | History | Annotate | Line # | Download | only in ps
ps.c revision 1.80
      1 /*	$NetBSD: ps.c,v 1.80 2014/02/19 20:42:14 dsl 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.80 2014/02/19 20:42:14 dsl 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 <kvm.h>
     90 #include <limits.h>
     91 #include <locale.h>
     92 #include <nlist.h>
     93 #include <paths.h>
     94 #include <pwd.h>
     95 #include <stdio.h>
     96 #include <stdlib.h>
     97 #include <string.h>
     98 #include <unistd.h>
     99 
    100 #include "ps.h"
    101 
    102 /*
    103  * ARGOPTS must contain all option characters that take arguments
    104  * (except for 't'!) - it is used in kludge_oldps_options()
    105  */
    106 #define	GETOPTSTR	"aAcCeghjk:LlM:mN:O:o:p:rSsTt:U:uvW:wx"
    107 #define	ARGOPTS		"kMNOopUW"
    108 
    109 struct kinfo_proc2 *kinfo;
    110 struct varlist displaylist = SIMPLEQ_HEAD_INITIALIZER(displaylist);
    111 struct varlist sortlist = SIMPLEQ_HEAD_INITIALIZER(sortlist);
    112 
    113 int	eval;			/* exit value */
    114 int	rawcpu;			/* -C */
    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 char	*kludge_oldps_options(char *);
    128 static int	 pscomp(const void *, const void *);
    129 static void	 scanvars(void);
    130 __dead static void	 usage(void);
    131 static int	 parsenum(const char *, const char *);
    132 int		 main(int, char *[]);
    133 
    134 char dfmt[] = "pid tt state time command";
    135 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
    136 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
    137 char sfmt[] = "uid pid ppid cpu lid nlwp pri nice vsz rss wchan lstate tt "
    138 		"ltime command";
    139 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
    140 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
    141 
    142 const char *default_fmt = dfmt;
    143 
    144 struct varent *Opos = NULL; /* -O flag inserts after this point */
    145 
    146 kvm_t *kd;
    147 
    148 static long long
    149 ttyname2dev(const char *ttname, int *xflg, int *what)
    150 {
    151 	struct stat sb;
    152 	const char *ttypath;
    153 	char pathbuf[MAXPATHLEN];
    154 
    155 	ttypath = NULL;
    156 	if (strcmp(ttname, "?") == 0) {
    157 		*xflg = 1;
    158 		return KERN_PROC_TTY_NODEV;
    159 	}
    160 	if (strcmp(ttname, "-") == 0)
    161 		return KERN_PROC_TTY_REVOKE;
    162 
    163 	if (strcmp(ttname, "co") == 0)
    164 		ttypath = _PATH_CONSOLE;
    165 	else if (strncmp(ttname, "pts/", 4) == 0 ||
    166 		strncmp(ttname, "tty", 3) == 0) {
    167 		(void)snprintf(pathbuf,
    168 		    sizeof(pathbuf), "%s%s", _PATH_DEV, ttname);
    169 		ttypath = pathbuf;
    170 	} else if (*ttname != '/') {
    171 		(void)snprintf(pathbuf,
    172 		    sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
    173 		ttypath = pathbuf;
    174 	} else
    175 		ttypath = ttname;
    176 	*what = KERN_PROC_TTY;
    177 	if (stat(ttypath, &sb) == -1) {
    178 		devmajor_t pts = getdevmajor("pts", S_IFCHR);
    179 
    180 		if (pts != NODEVMAJOR && strncmp(ttname, "pts/", 4) == 0) {
    181 			int ptsminor = atoi(ttname + 4);
    182 
    183 			snprintf(pathbuf, sizeof(pathbuf), "pts/%d", ptsminor);
    184 			if (strcmp(pathbuf, ttname) == 0 && ptsminor >= 0)
    185 				return makedev(pts, ptsminor);
    186 		}
    187 		err(1, "%s", ttypath);
    188 	}
    189 	if (!S_ISCHR(sb.st_mode))
    190 		errx(1, "%s: not a terminal", ttypath);
    191 	return sb.st_rdev;
    192 }
    193 
    194 int
    195 main(int argc, char *argv[])
    196 {
    197 	struct varent *vent;
    198 	struct winsize ws;
    199 	struct kinfo_lwp *kl, *l;
    200 	int ch, i, j, fmt, lineno, nentries, nlwps;
    201 	long long flag;
    202 	int prtheader, wflag, what, xflg, mode, showlwps;
    203 	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
    204 	char *ttname;
    205 
    206 	setprogname(argv[0]);
    207 	(void)setlocale(LC_ALL, "");
    208 
    209 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    210 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    211 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
    212 	     ws.ws_col == 0)
    213 		termwidth = 79;
    214 	else
    215 		termwidth = ws.ws_col - 1;
    216 
    217 	if (argc > 1)
    218 		argv[1] = kludge_oldps_options(argv[1]);
    219 
    220 	fmt = prtheader = wflag = xflg = showlwps = 0;
    221 	what = KERN_PROC_UID;
    222 	flag = myuid = getuid();
    223 	memf = nlistf = swapf = NULL;
    224 	mode = PRINTMODE;
    225 	while ((ch = getopt(argc, argv, GETOPTSTR)) != -1)
    226 		switch((char)ch) {
    227 		case 'A':
    228 			/* "-A" shows all processes, like "-ax" */
    229 			xflg = 1;
    230 			/*FALLTHROUGH*/
    231 		case 'a':
    232 			what = KERN_PROC_ALL;
    233 			flag = 0;
    234 			break;
    235 		case 'c':
    236 			commandonly = 1;
    237 			break;
    238 		case 'e':			/* XXX set ufmt */
    239 			needenv = 1;
    240 			break;
    241 		case 'C':
    242 			rawcpu = 1;
    243 			break;
    244 		case 'g':
    245 			break;			/* no-op */
    246 		case 'h':
    247 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
    248 			break;
    249 		case 'j':
    250 			parsefmt(jfmt);
    251 			fmt = 1;
    252 			jfmt[0] = '\0';
    253 			break;
    254 		case 'k':
    255 			parsesort(optarg);
    256 			break;
    257 		case 'K':
    258 			break;			/* no-op - was dontuseprocfs */
    259 		case 'L':
    260 			showkey();
    261 			exit(0);
    262 			/* NOTREACHED */
    263 		case 'l':
    264 			parsefmt(lfmt);
    265 			fmt = 1;
    266 			lfmt[0] = '\0';
    267 			break;
    268 		case 'M':
    269 			memf = optarg;
    270 			break;
    271 		case 'm':
    272 			parsesort("vsz");
    273 			break;
    274 		case 'N':
    275 			nlistf = optarg;
    276 			break;
    277 		case 'O':
    278 			/*
    279 			 * If this is not the first -O option, insert
    280 			 * just after the previous one.
    281 			 *
    282 			 * If there is no format yet, start with the default
    283 			 * format, and insert after the pid column.
    284 			 *
    285 			 * If there is already a format, insert after
    286 			 * the pid column, or at the end if there's no
    287 			 * pid column.
    288 			 */
    289 			if (!Opos) {
    290 				if (!fmt)
    291 					parsefmt(default_fmt);
    292 				Opos = varlist_find(&displaylist, "pid");
    293 			}
    294 			parsefmt_insert(optarg, &Opos);
    295 			fmt = 1;
    296 			break;
    297 		case 'o':
    298 			parsefmt(optarg);
    299 			fmt = 1;
    300 			break;
    301 		case 'p':
    302 			what = KERN_PROC_PID;
    303 			flag = parsenum(optarg, "process id");
    304 			xflg = 1;
    305 			break;
    306 		case 'r':
    307 			parsesort("%cpu");
    308 			break;
    309 		case 'S':
    310 			sumrusage = 1;
    311 			break;
    312 		case 's':
    313 			/* -L was already taken... */
    314 			showlwps = 1;
    315 			default_fmt = sfmt;
    316 			break;
    317 		case 'T':
    318 			if ((ttname = ttyname(STDIN_FILENO)) == NULL)
    319 				errx(1, "stdin: not a terminal");
    320 			flag = ttyname2dev(ttname, &xflg, &what);
    321 			break;
    322 		case 't':
    323 			flag = ttyname2dev(optarg, &xflg, &what);
    324 			break;
    325 		case 'U':
    326 			if (*optarg != '\0') {
    327 				struct passwd *pw;
    328 
    329 				what = KERN_PROC_UID;
    330 				pw = getpwnam(optarg);
    331 				if (pw == NULL) {
    332 					flag = parsenum(optarg, "user name");
    333 				} else
    334 					flag = pw->pw_uid;
    335 			}
    336 			break;
    337 		case 'u':
    338 			parsefmt(ufmt);
    339 			parsesort("%cpu");
    340 			fmt = 1;
    341 			ufmt[0] = '\0';
    342 			break;
    343 		case 'v':
    344 			parsefmt(vfmt);
    345 			parsesort("vsz");
    346 			fmt = 1;
    347 			vfmt[0] = '\0';
    348 			break;
    349 		case 'W':
    350 			swapf = optarg;
    351 			break;
    352 		case 'w':
    353 			if (wflag)
    354 				termwidth = UNLIMITED;
    355 			else if (termwidth < 131)
    356 				termwidth = 131;
    357 			wflag++;
    358 			break;
    359 		case 'x':
    360 			xflg = 1;
    361 			break;
    362 		case '?':
    363 		default:
    364 			usage();
    365 		}
    366 	argc -= optind;
    367 	argv += optind;
    368 
    369 #define	BACKWARD_COMPATIBILITY
    370 #ifdef	BACKWARD_COMPATIBILITY
    371 	if (*argv) {
    372 		nlistf = *argv;
    373 		if (*++argv) {
    374 			memf = *argv;
    375 			if (*++argv)
    376 				swapf = *argv;
    377 		}
    378 	}
    379 #endif
    380 
    381 	if (memf == NULL) {
    382 		kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
    383 		donlist_sysctl();
    384 	} else
    385 		kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
    386 
    387 	if (kd == 0)
    388 		errx(1, "%s", errbuf);
    389 
    390 	if (!fmt)
    391 		parsefmt(default_fmt);
    392 
    393 	/* Add default sort criteria */
    394 	parsesort("tdev,pid");
    395 	SIMPLEQ_FOREACH(vent, &sortlist, next) {
    396 		if (vent->var->flag & LWP || vent->var->type == UNSPECIFIED)
    397 			warnx("Cannot sort on %s, sort key ignored\n",
    398 				vent->var->name);
    399 	}
    400 
    401 	/*
    402 	 * scan requested variables, noting what structures are needed.
    403 	 */
    404 	scanvars();
    405 
    406 	/*
    407 	 * select procs
    408 	 */
    409 	if (!(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
    410 		err(1, "%s", kvm_geterr(kd));
    411 	if (nentries == 0) {
    412 		printheader();
    413 		exit(1);
    414 	}
    415 	/*
    416 	 * sort proc list
    417 	 */
    418 	qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
    419 	/*
    420 	 * For each proc, call each variable output function in
    421 	 * "setwidth" mode to determine the widest element of
    422 	 * the column.
    423 	 */
    424 	if (mode == PRINTMODE)
    425 		for (i = 0; i < nentries; i++) {
    426 			struct kinfo_proc2 *ki = &kinfo[i];
    427 
    428 			if (xflg == 0 && (ki->p_tdev == (uint32_t)NODEV ||
    429 			    (ki->p_flag & P_CONTROLT) == 0))
    430 				continue;
    431 
    432 			kl = kvm_getlwps(kd, ki->p_pid, ki->p_paddr,
    433 			    sizeof(struct kinfo_lwp), &nlwps);
    434 			if (kl == 0)
    435 				nlwps = 0;
    436 			if (showlwps == 0) {
    437 				l = pick_representative_lwp(ki, kl, nlwps);
    438 				SIMPLEQ_FOREACH(vent, &displaylist, next)
    439 					OUTPUT(vent, ki, l, WIDTHMODE);
    440 			} else {
    441 				/* The printing is done with the loops
    442 				 * reversed, but here we don't need that,
    443 				 * and this improves the code locality a bit.
    444 				 */
    445 				SIMPLEQ_FOREACH(vent, &displaylist, next)
    446 					for (j = 0; j < nlwps; j++)
    447 						OUTPUT(vent, ki, &kl[j],
    448 						    WIDTHMODE);
    449 			}
    450 		}
    451 	/*
    452 	 * Print header - AFTER determining process field widths.
    453 	 * printheader() also adds up the total width of all
    454 	 * fields the first time it's called.
    455 	 */
    456 	printheader();
    457 	/*
    458 	 * For each proc, call each variable output function in
    459 	 * print mode.
    460 	 */
    461 	for (i = lineno = 0; i < nentries; i++) {
    462 		struct kinfo_proc2 *ki = &kinfo[i];
    463 
    464 		if (xflg == 0 && (ki->p_tdev == (uint32_t)NODEV ||
    465 		    (ki->p_flag & P_CONTROLT ) == 0))
    466 			continue;
    467 		kl = kvm_getlwps(kd, ki->p_pid, (u_long)ki->p_paddr,
    468 		    sizeof(struct kinfo_lwp), &nlwps);
    469 		if (kl == 0)
    470 			nlwps = 0;
    471 		if (showlwps == 0) {
    472 			l = pick_representative_lwp(ki, kl, nlwps);
    473 			SIMPLEQ_FOREACH(vent, &displaylist, next) {
    474 				OUTPUT(vent, ki, l, mode);
    475 				if (SIMPLEQ_NEXT(vent, next) != NULL)
    476 					(void)putchar(' ');
    477 			}
    478 			(void)putchar('\n');
    479 			if (prtheader && lineno++ == prtheader - 4) {
    480 				(void)putchar('\n');
    481 				printheader();
    482 				lineno = 0;
    483 			}
    484 		} else {
    485 			for (j = 0; j < nlwps; j++) {
    486 				SIMPLEQ_FOREACH(vent, &displaylist, next) {
    487 					OUTPUT(vent, ki, &kl[j], mode);
    488 					if (SIMPLEQ_NEXT(vent, next) != NULL)
    489 						(void)putchar(' ');
    490 				}
    491 				(void)putchar('\n');
    492 				if (prtheader && lineno++ == prtheader - 4) {
    493 					(void)putchar('\n');
    494 					printheader();
    495 					lineno = 0;
    496 				}
    497 			}
    498 		}
    499 	}
    500 	exit(eval);
    501 	/* NOTREACHED */
    502 }
    503 
    504 static struct kinfo_lwp *
    505 pick_representative_lwp(struct kinfo_proc2 *ki, struct kinfo_lwp *kl, int nlwps)
    506 {
    507 	int i, onproc, running, sleeping, stopped, suspended;
    508 	static struct kinfo_lwp zero_lwp;
    509 
    510 	if (kl == 0)
    511 		return &zero_lwp;
    512 
    513 	/* Trivial case: only one LWP */
    514 	if (nlwps == 1)
    515 		return kl;
    516 
    517 	switch (ki->p_realstat) {
    518 	case SSTOP:
    519 	case SACTIVE:
    520 		/* Pick the most live LWP */
    521 		onproc = running = sleeping = stopped = suspended = -1;
    522 		for (i = 0; i < nlwps; i++) {
    523 			switch (kl[i].l_stat) {
    524 			case LSONPROC:
    525 				onproc = i;
    526 				break;
    527 			case LSRUN:
    528 				running = i;
    529 				break;
    530 			case LSSLEEP:
    531 				sleeping = i;
    532 				break;
    533 			case LSSTOP:
    534 				stopped = i;
    535 				break;
    536 			case LSSUSPENDED:
    537 				suspended = i;
    538 				break;
    539 			}
    540 		}
    541 		if (onproc != -1)
    542 			return &kl[onproc];
    543 		if (running != -1)
    544 			return &kl[running];
    545 		if (sleeping != -1)
    546 			return &kl[sleeping];
    547 		if (stopped != -1)
    548 			return &kl[stopped];
    549 		if (suspended != -1)
    550 			return &kl[suspended];
    551 		break;
    552 	case SZOMB:
    553 		/* First will do */
    554 		return kl;
    555 		break;
    556 	}
    557 	/* Error condition! */
    558 	warnx("Inconsistent LWP state for process %d\n", ki->p_pid);
    559 	return kl;
    560 }
    561 
    562 
    563 static struct kinfo_proc2 *
    564 getkinfo_kvm(kvm_t *kdp, int what, int flag, int *nentriesp)
    565 {
    566 
    567 	return (kvm_getproc2(kdp, what, flag, sizeof(struct kinfo_proc2),
    568 	    nentriesp));
    569 }
    570 
    571 static void
    572 scanvars(void)
    573 {
    574 	struct varent *vent;
    575 	VAR *v;
    576 
    577 	SIMPLEQ_FOREACH(vent, &displaylist, next) {
    578 		v = vent->var;
    579 		if (v->flag & COMM) {
    580 			needcomm = 1;
    581 			break;
    582 		}
    583 	}
    584 }
    585 
    586 static int
    587 pscomp(const void *a, const void *b)
    588 {
    589 	const struct kinfo_proc2 *ka = (const struct kinfo_proc2 *)a;
    590 	const struct kinfo_proc2 *kb = (const struct kinfo_proc2 *)b;
    591 
    592 	int i;
    593 	int64_t i64;
    594 	VAR *v;
    595 	struct varent *ve;
    596 	const sigset_t *sa, *sb;
    597 
    598 #define	V_SIZE(k) ((k)->p_vm_msize)
    599 #define	RDIFF_N(t, n) \
    600 	if (((const t *)((const char *)ka + v->off))[n] > ((const t *)((const char *)kb + v->off))[n]) \
    601 		return 1; \
    602 	if (((const t *)((const char *)ka + v->off))[n] < ((const t *)((const char *)kb + v->off))[n]) \
    603 		return -1;
    604 
    605 #define	RDIFF(type) RDIFF_N(type, 0); continue
    606 
    607 	SIMPLEQ_FOREACH(ve, &sortlist, next) {
    608 		v = ve->var;
    609 		if (v->flag & LWP)
    610 			/* LWP structure not available (yet) */
    611 			continue;
    612 		/* Sort on pvar() fields, + a few others */
    613 		switch (v->type) {
    614 		case CHAR:
    615 			RDIFF(char);
    616 		case UCHAR:
    617 			RDIFF(u_char);
    618 		case SHORT:
    619 			RDIFF(short);
    620 		case USHORT:
    621 			RDIFF(ushort);
    622 		case INT:
    623 			RDIFF(int);
    624 		case UINT:
    625 			RDIFF(uint);
    626 		case LONG:
    627 			RDIFF(long);
    628 		case ULONG:
    629 			RDIFF(ulong);
    630 		case INT32:
    631 			RDIFF(int32_t);
    632 		case UINT32:
    633 			RDIFF(uint32_t);
    634 		case SIGLIST:
    635 			sa = (const void *)((const char *)a + v->off);
    636 			sb = (const void *)((const char *)b + v->off);
    637 			i = 0;
    638 			do {
    639 				if (sa->__bits[i] > sb->__bits[i])
    640 					return 1;
    641 				if (sa->__bits[i] < sb->__bits[i])
    642 					return -1;
    643 				i++;
    644 			} while (i < (int)__arraycount(sa->__bits));
    645 			continue;
    646 		case INT64:
    647 			RDIFF(int64_t);
    648 		case KPTR:
    649 		case KPTR24:
    650 		case UINT64:
    651 			RDIFF(uint64_t);
    652 		case TIMEVAL:
    653 			/* compare xxx_sec then xxx_usec */
    654 			RDIFF_N(uint32_t, 0);
    655 			RDIFF_N(uint32_t, 1);
    656 			continue;
    657 		case CPUTIME:
    658 			i64 = ka->p_rtime_sec * 1000000 + ka->p_rtime_usec;
    659 			i64 -= kb->p_rtime_sec * 1000000 + kb->p_rtime_usec;
    660 			if (sumrusage) {
    661 				i64 += ka->p_uctime_sec * 1000000
    662 				    + ka->p_uctime_usec;
    663 				i64 -= kb->p_uctime_sec * 1000000
    664 				    + kb->p_uctime_usec;
    665 			}
    666 			if (i64 != 0)
    667 				return i64 > 0 ? 1 : -1;
    668 			continue;
    669 		case PCPU:
    670 			i = getpcpu(kb) - getpcpu(ka);
    671 			if (i != 0)
    672 				return i;
    673 			continue;
    674 		case VSIZE:
    675 			i = V_SIZE(kb) - V_SIZE(ka);
    676 			if (i != 0)
    677 				return i;
    678 			continue;
    679 
    680 		default:
    681 			/* Ignore everything else */
    682 			break;
    683 		}
    684 	}
    685 	return 0;
    686 
    687 #undef VSIZE
    688 }
    689 
    690 /*
    691  * ICK (all for getopt), would rather hide the ugliness
    692  * here than taint the main code.
    693  *
    694  *  ps foo -> ps -foo
    695  *  ps 34 -> ps -p34
    696  *
    697  * The old convention that 't' with no trailing tty arg means the user's
    698  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
    699  * feature is available with the option 'T', which takes no argument.
    700  */
    701 static char *
    702 kludge_oldps_options(char *s)
    703 {
    704 	size_t len;
    705 	char *newopts, *ns, *cp;
    706 
    707 	len = strlen(s);
    708 	if ((newopts = ns = malloc(len + 3)) == NULL)
    709 		err(1, NULL);
    710 	/*
    711 	 * options begin with '-'
    712 	 */
    713 	if (*s != '-')
    714 		*ns++ = '-';	/* add option flag */
    715 	/*
    716 	 * gaze to end of argv[1]
    717 	 */
    718 	cp = s + len - 1;
    719 	/*
    720 	 * if the last letter is a 't' flag and there are no other option
    721 	 * characters that take arguments (eg U, p, o) in the option
    722 	 * string and the option string doesn't start with a '-' then
    723 	 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
    724 	 */
    725 	if (*cp == 't' && *s != '-' && strpbrk(s, ARGOPTS) == NULL)
    726 		*cp = 'T';
    727 	else {
    728 		/*
    729 		 * otherwise check for trailing number, which *may* be a
    730 		 * pid.
    731 		 */
    732 		while (cp >= s && isdigit((unsigned char)*cp))
    733 			--cp;
    734 	}
    735 	cp++;
    736 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
    737 	ns += cp - s;
    738 	/*
    739 	 * if there's a trailing number, and not a preceding 'p' (pid) or
    740 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
    741 	 */
    742 	if (isdigit((unsigned char)*cp) &&
    743 	    (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
    744 	    cp[-1] != '/' && (cp - 1 == s || cp[-2] != 't'))))
    745 		*ns++ = 'p';
    746 	/* and append the number */
    747 	(void)strcpy(ns, cp);		/* XXX strcpy is safe here */
    748 
    749 	return (newopts);
    750 }
    751 
    752 static int
    753 parsenum(const char *str, const char *msg)
    754 {
    755 	char *ep;
    756 	unsigned long ul;
    757 
    758 	ul = strtoul(str, &ep, 0);
    759 
    760 	if (*str == '\0' || *ep != '\0')
    761 		errx(1, "Invalid %s: `%s'", msg, str);
    762 
    763 	if (ul > INT_MAX)
    764 		errx(1, "Out of range %s: `%s'", msg, str);
    765 
    766 	return (int)ul;
    767 }
    768 
    769 static void
    770 usage(void)
    771 {
    772 
    773 	(void)fprintf(stderr,
    774 	    "usage:\t%s\n\t   %s\n\t%s\n",
    775 	    "ps [-AaCcehjlmrSsTuvwx] [-k key] [-M core] [-N system] [-O fmt]",
    776 	    "[-o fmt] [-p pid] [-t tty] [-U user] [-W swap]",
    777 	    "ps -L");
    778 	exit(1);
    779 	/* NOTREACHED */
    780 }
    781