xref: /netbsd-src/bin/ps/ps.c (revision 2c6fc41c810f5088457889d00eba558e8bc74d9e)
1 /*	$NetBSD: ps.c,v 1.81 2014/04/20 23:31:40 dholland 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.81 2014/04/20 23:31:40 dholland 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, 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 
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 
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], WIDTHMODE);
448 		}
449 	}
450 	/*
451 	 * Print header - AFTER determining process field widths.
452 	 * printheader() also adds up the total width of all
453 	 * fields the first time it's called.
454 	 */
455 	printheader();
456 	/*
457 	 * For each proc, call each variable output function in
458 	 * print mode.
459 	 */
460 	for (i = lineno = 0; i < nentries; i++) {
461 		struct kinfo_proc2 *ki = &kinfo[i];
462 
463 		if (xflg == 0 && (ki->p_tdev == (uint32_t)NODEV ||
464 		    (ki->p_flag & P_CONTROLT ) == 0))
465 			continue;
466 		kl = kvm_getlwps(kd, ki->p_pid, (u_long)ki->p_paddr,
467 		    sizeof(struct kinfo_lwp), &nlwps);
468 		if (kl == 0)
469 			nlwps = 0;
470 		if (showlwps == 0) {
471 			l = pick_representative_lwp(ki, kl, nlwps);
472 			SIMPLEQ_FOREACH(vent, &displaylist, next) {
473 				OUTPUT(vent, ki, l, PRINTMODE);
474 				if (SIMPLEQ_NEXT(vent, next) != NULL)
475 					(void)putchar(' ');
476 			}
477 			(void)putchar('\n');
478 			if (prtheader && lineno++ == prtheader - 4) {
479 				(void)putchar('\n');
480 				printheader();
481 				lineno = 0;
482 			}
483 		} else {
484 			for (j = 0; j < nlwps; j++) {
485 				SIMPLEQ_FOREACH(vent, &displaylist, next) {
486 					OUTPUT(vent, ki, &kl[j], PRINTMODE);
487 					if (SIMPLEQ_NEXT(vent, next) != NULL)
488 						(void)putchar(' ');
489 				}
490 				(void)putchar('\n');
491 				if (prtheader && lineno++ == prtheader - 4) {
492 					(void)putchar('\n');
493 					printheader();
494 					lineno = 0;
495 				}
496 			}
497 		}
498 	}
499 	exit(eval);
500 	/* NOTREACHED */
501 }
502 
503 static struct kinfo_lwp *
504 pick_representative_lwp(struct kinfo_proc2 *ki, struct kinfo_lwp *kl, int nlwps)
505 {
506 	int i, onproc, running, sleeping, stopped, suspended;
507 	static struct kinfo_lwp zero_lwp;
508 
509 	if (kl == 0)
510 		return &zero_lwp;
511 
512 	/* Trivial case: only one LWP */
513 	if (nlwps == 1)
514 		return kl;
515 
516 	switch (ki->p_realstat) {
517 	case SSTOP:
518 	case SACTIVE:
519 		/* Pick the most live LWP */
520 		onproc = running = sleeping = stopped = suspended = -1;
521 		for (i = 0; i < nlwps; i++) {
522 			switch (kl[i].l_stat) {
523 			case LSONPROC:
524 				onproc = i;
525 				break;
526 			case LSRUN:
527 				running = i;
528 				break;
529 			case LSSLEEP:
530 				sleeping = i;
531 				break;
532 			case LSSTOP:
533 				stopped = i;
534 				break;
535 			case LSSUSPENDED:
536 				suspended = i;
537 				break;
538 			}
539 		}
540 		if (onproc != -1)
541 			return &kl[onproc];
542 		if (running != -1)
543 			return &kl[running];
544 		if (sleeping != -1)
545 			return &kl[sleeping];
546 		if (stopped != -1)
547 			return &kl[stopped];
548 		if (suspended != -1)
549 			return &kl[suspended];
550 		break;
551 	case SZOMB:
552 		/* First will do */
553 		return kl;
554 		break;
555 	}
556 	/* Error condition! */
557 	warnx("Inconsistent LWP state for process %d\n", ki->p_pid);
558 	return kl;
559 }
560 
561 
562 static struct kinfo_proc2 *
563 getkinfo_kvm(kvm_t *kdp, int what, int flag, int *nentriesp)
564 {
565 
566 	return (kvm_getproc2(kdp, what, flag, sizeof(struct kinfo_proc2),
567 	    nentriesp));
568 }
569 
570 static void
571 scanvars(void)
572 {
573 	struct varent *vent;
574 	VAR *v;
575 
576 	SIMPLEQ_FOREACH(vent, &displaylist, next) {
577 		v = vent->var;
578 		if (v->flag & COMM) {
579 			needcomm = 1;
580 			break;
581 		}
582 	}
583 }
584 
585 static int
586 pscomp(const void *a, const void *b)
587 {
588 	const struct kinfo_proc2 *ka = (const struct kinfo_proc2 *)a;
589 	const struct kinfo_proc2 *kb = (const struct kinfo_proc2 *)b;
590 
591 	int i;
592 	int64_t i64;
593 	VAR *v;
594 	struct varent *ve;
595 	const sigset_t *sa, *sb;
596 
597 #define	V_SIZE(k) ((k)->p_vm_msize)
598 #define	RDIFF_N(t, n) \
599 	if (((const t *)((const char *)ka + v->off))[n] > ((const t *)((const char *)kb + v->off))[n]) \
600 		return 1; \
601 	if (((const t *)((const char *)ka + v->off))[n] < ((const t *)((const char *)kb + v->off))[n]) \
602 		return -1;
603 
604 #define	RDIFF(type) RDIFF_N(type, 0); continue
605 
606 	SIMPLEQ_FOREACH(ve, &sortlist, next) {
607 		v = ve->var;
608 		if (v->flag & LWP)
609 			/* LWP structure not available (yet) */
610 			continue;
611 		/* Sort on pvar() fields, + a few others */
612 		switch (v->type) {
613 		case CHAR:
614 			RDIFF(char);
615 		case UCHAR:
616 			RDIFF(u_char);
617 		case SHORT:
618 			RDIFF(short);
619 		case USHORT:
620 			RDIFF(ushort);
621 		case INT:
622 			RDIFF(int);
623 		case UINT:
624 			RDIFF(uint);
625 		case LONG:
626 			RDIFF(long);
627 		case ULONG:
628 			RDIFF(ulong);
629 		case INT32:
630 			RDIFF(int32_t);
631 		case UINT32:
632 			RDIFF(uint32_t);
633 		case SIGLIST:
634 			sa = (const void *)((const char *)a + v->off);
635 			sb = (const void *)((const char *)b + v->off);
636 			i = 0;
637 			do {
638 				if (sa->__bits[i] > sb->__bits[i])
639 					return 1;
640 				if (sa->__bits[i] < sb->__bits[i])
641 					return -1;
642 				i++;
643 			} while (i < (int)__arraycount(sa->__bits));
644 			continue;
645 		case INT64:
646 			RDIFF(int64_t);
647 		case KPTR:
648 		case KPTR24:
649 		case UINT64:
650 			RDIFF(uint64_t);
651 		case TIMEVAL:
652 			/* compare xxx_sec then xxx_usec */
653 			RDIFF_N(uint32_t, 0);
654 			RDIFF_N(uint32_t, 1);
655 			continue;
656 		case CPUTIME:
657 			i64 = ka->p_rtime_sec * 1000000 + ka->p_rtime_usec;
658 			i64 -= kb->p_rtime_sec * 1000000 + kb->p_rtime_usec;
659 			if (sumrusage) {
660 				i64 += ka->p_uctime_sec * 1000000
661 				    + ka->p_uctime_usec;
662 				i64 -= kb->p_uctime_sec * 1000000
663 				    + kb->p_uctime_usec;
664 			}
665 			if (i64 != 0)
666 				return i64 > 0 ? 1 : -1;
667 			continue;
668 		case PCPU:
669 			i = getpcpu(kb) - getpcpu(ka);
670 			if (i != 0)
671 				return i;
672 			continue;
673 		case VSIZE:
674 			i = V_SIZE(kb) - V_SIZE(ka);
675 			if (i != 0)
676 				return i;
677 			continue;
678 
679 		default:
680 			/* Ignore everything else */
681 			break;
682 		}
683 	}
684 	return 0;
685 
686 #undef VSIZE
687 }
688 
689 /*
690  * ICK (all for getopt), would rather hide the ugliness
691  * here than taint the main code.
692  *
693  *  ps foo -> ps -foo
694  *  ps 34 -> ps -p34
695  *
696  * The old convention that 't' with no trailing tty arg means the user's
697  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
698  * feature is available with the option 'T', which takes no argument.
699  */
700 static char *
701 kludge_oldps_options(char *s)
702 {
703 	size_t len;
704 	char *newopts, *ns, *cp;
705 
706 	len = strlen(s);
707 	if ((newopts = ns = malloc(len + 3)) == NULL)
708 		err(1, NULL);
709 	/*
710 	 * options begin with '-'
711 	 */
712 	if (*s != '-')
713 		*ns++ = '-';	/* add option flag */
714 	/*
715 	 * gaze to end of argv[1]
716 	 */
717 	cp = s + len - 1;
718 	/*
719 	 * if the last letter is a 't' flag and there are no other option
720 	 * characters that take arguments (eg U, p, o) in the option
721 	 * string and the option string doesn't start with a '-' then
722 	 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
723 	 */
724 	if (*cp == 't' && *s != '-' && strpbrk(s, ARGOPTS) == NULL)
725 		*cp = 'T';
726 	else {
727 		/*
728 		 * otherwise check for trailing number, which *may* be a
729 		 * pid.
730 		 */
731 		while (cp >= s && isdigit((unsigned char)*cp))
732 			--cp;
733 	}
734 	cp++;
735 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
736 	ns += cp - s;
737 	/*
738 	 * if there's a trailing number, and not a preceding 'p' (pid) or
739 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
740 	 */
741 	if (isdigit((unsigned char)*cp) &&
742 	    (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
743 	    cp[-1] != '/' && (cp - 1 == s || cp[-2] != 't'))))
744 		*ns++ = 'p';
745 	/* and append the number */
746 	(void)strcpy(ns, cp);		/* XXX strcpy is safe here */
747 
748 	return (newopts);
749 }
750 
751 static int
752 parsenum(const char *str, const char *msg)
753 {
754 	char *ep;
755 	unsigned long ul;
756 
757 	ul = strtoul(str, &ep, 0);
758 
759 	if (*str == '\0' || *ep != '\0')
760 		errx(1, "Invalid %s: `%s'", msg, str);
761 
762 	if (ul > INT_MAX)
763 		errx(1, "Out of range %s: `%s'", msg, str);
764 
765 	return (int)ul;
766 }
767 
768 static void
769 usage(void)
770 {
771 
772 	(void)fprintf(stderr,
773 	    "usage:\t%s\n\t   %s\n\t%s\n",
774 	    "ps [-AaCcehjlmrSsTuvwx] [-k key] [-M core] [-N system] [-O fmt]",
775 	    "[-o fmt] [-p pid] [-t tty] [-U user] [-W swap]",
776 	    "ps -L");
777 	exit(1);
778 	/* NOTREACHED */
779 }
780