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