ps.c revision 1.85 1 /* $NetBSD: ps.c,v 1.85 2016/11/28 08:18:27 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.85 2016/11/28 08:18:27 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 <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
133 char dfmt[] = "pid tt state time command";
134 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
135 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
136 char sfmt[] = "uid pid ppid cpu lid nlwp pri nice vsz rss wchan lstate tt "
137 "ltime command";
138 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
139 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
140
141 const char *default_fmt = dfmt;
142
143 struct varent *Opos = NULL; /* -O flag inserts after this point */
144
145 kvm_t *kd;
146
147 static long long
148 ttyname2dev(const char *ttname, int *xflg, int *what)
149 {
150 struct stat sb;
151 const char *ttypath;
152 char pathbuf[MAXPATHLEN];
153
154 ttypath = NULL;
155 if (strcmp(ttname, "?") == 0) {
156 *xflg = 1;
157 return KERN_PROC_TTY_NODEV;
158 }
159 if (strcmp(ttname, "-") == 0)
160 return KERN_PROC_TTY_REVOKE;
161
162 if (strcmp(ttname, "co") == 0)
163 ttypath = _PATH_CONSOLE;
164 else if (strncmp(ttname, "pts/", 4) == 0 ||
165 strncmp(ttname, "tty", 3) == 0) {
166 (void)snprintf(pathbuf,
167 sizeof(pathbuf), "%s%s", _PATH_DEV, ttname);
168 ttypath = pathbuf;
169 } else if (*ttname != '/') {
170 (void)snprintf(pathbuf,
171 sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
172 ttypath = pathbuf;
173 } else
174 ttypath = ttname;
175 *what = KERN_PROC_TTY;
176 if (stat(ttypath, &sb) == -1) {
177 devmajor_t pts;
178 int serrno;
179
180 serrno = errno;
181 pts = getdevmajor("pts", S_IFCHR);
182 if (pts != NODEVMAJOR && strncmp(ttname, "pts/", 4) == 0) {
183 int ptsminor = atoi(ttname + 4);
184
185 snprintf(pathbuf, sizeof(pathbuf), "pts/%d", ptsminor);
186 if (strcmp(pathbuf, ttname) == 0 && ptsminor >= 0)
187 return makedev(pts, ptsminor);
188 }
189 errno = serrno;
190 err(1, "%s", ttypath);
191 }
192 if (!S_ISCHR(sb.st_mode))
193 errx(1, "%s: not a terminal", ttypath);
194 return sb.st_rdev;
195 }
196
197 int
198 main(int argc, char *argv[])
199 {
200 struct varent *vent;
201 struct winsize ws;
202 struct kinfo_lwp *kl, *l;
203 int ch, i, j, fmt, lineno, nentries, nlwps;
204 long long flag;
205 int prtheader, wflag, what, xflg, showlwps;
206 char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
207 char *ttname;
208
209 setprogname(argv[0]);
210 (void)setlocale(LC_ALL, "");
211
212 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
213 ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
214 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ws) == -1) ||
215 ws.ws_col == 0)
216 termwidth = 79;
217 else
218 termwidth = ws.ws_col - 1;
219
220 if (argc > 1)
221 argv[1] = kludge_oldps_options(argv[1]);
222
223 fmt = prtheader = wflag = xflg = showlwps = 0;
224 what = KERN_PROC_UID;
225 flag = myuid = getuid();
226 memf = nlistf = swapf = NULL;
227
228 while ((ch = getopt(argc, argv, GETOPTSTR)) != -1)
229 switch((char)ch) {
230 case 'A':
231 /* "-A" shows all processes, like "-ax" */
232 xflg = 1;
233 /*FALLTHROUGH*/
234 case 'a':
235 what = KERN_PROC_ALL;
236 flag = 0;
237 break;
238 case 'c':
239 commandonly = 1;
240 break;
241 case 'e': /* XXX set ufmt */
242 needenv = 1;
243 break;
244 case 'C':
245 rawcpu = 1;
246 break;
247 case 'g':
248 break; /* no-op */
249 case 'h':
250 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
251 break;
252 case 'j':
253 parsefmt(jfmt);
254 fmt = 1;
255 jfmt[0] = '\0';
256 break;
257 case 'k':
258 parsesort(optarg);
259 break;
260 case 'K':
261 break; /* no-op - was dontuseprocfs */
262 case 'L':
263 showkey();
264 return 0;
265 case 'l':
266 parsefmt(lfmt);
267 fmt = 1;
268 lfmt[0] = '\0';
269 break;
270 case 'M':
271 memf = optarg;
272 break;
273 case 'm':
274 parsesort("vsz");
275 break;
276 case 'N':
277 nlistf = optarg;
278 break;
279 case 'O':
280 /*
281 * If this is not the first -O option, insert
282 * just after the previous one.
283 *
284 * If there is no format yet, start with the default
285 * format, and insert after the pid column.
286 *
287 * If there is already a format, insert after
288 * the pid column, or at the end if there's no
289 * pid column.
290 */
291 if (!Opos) {
292 if (!fmt)
293 parsefmt(default_fmt);
294 Opos = varlist_find(&displaylist, "pid");
295 }
296 parsefmt_insert(optarg, &Opos);
297 fmt = 1;
298 break;
299 case 'o':
300 parsefmt(optarg);
301 fmt = 1;
302 break;
303 case 'p':
304 what = KERN_PROC_PID;
305 flag = parsenum(optarg, "process id");
306 xflg = 1;
307 break;
308 case 'r':
309 parsesort("%cpu");
310 break;
311 case 'S':
312 sumrusage = 1;
313 break;
314 case 's':
315 /* -L was already taken... */
316 showlwps = 1;
317 default_fmt = sfmt;
318 break;
319 case 'T':
320 if ((ttname = ttyname(STDIN_FILENO)) == NULL)
321 errx(1, "stdin: not a terminal");
322 flag = ttyname2dev(ttname, &xflg, &what);
323 break;
324 case 't':
325 flag = ttyname2dev(optarg, &xflg, &what);
326 break;
327 case 'U':
328 if (*optarg != '\0') {
329 struct passwd *pw;
330
331 what = KERN_PROC_UID;
332 pw = getpwnam(optarg);
333 if (pw == NULL) {
334 flag = parsenum(optarg, "user name");
335 } else
336 flag = pw->pw_uid;
337 }
338 break;
339 case 'u':
340 parsefmt(ufmt);
341 parsesort("%cpu");
342 fmt = 1;
343 ufmt[0] = '\0';
344 break;
345 case 'v':
346 parsefmt(vfmt);
347 parsesort("vsz");
348 fmt = 1;
349 vfmt[0] = '\0';
350 break;
351 case 'W':
352 swapf = optarg;
353 break;
354 case 'w':
355 if (wflag)
356 termwidth = UNLIMITED;
357 else if (termwidth < 131)
358 termwidth = 131;
359 wflag++;
360 break;
361 case 'x':
362 xflg = 1;
363 break;
364 case '?':
365 default:
366 usage();
367 }
368 argc -= optind;
369 argv += optind;
370
371 #define BACKWARD_COMPATIBILITY
372 #ifdef BACKWARD_COMPATIBILITY
373 if (*argv) {
374 nlistf = *argv;
375 if (*++argv) {
376 memf = *argv;
377 if (*++argv)
378 swapf = *argv;
379 }
380 }
381 #endif
382
383 if (memf == NULL) {
384 kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
385 donlist_sysctl();
386 } else
387 kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
388
389 if (kd == NULL)
390 errx(1, "%s", errbuf);
391
392 if (!fmt)
393 parsefmt(default_fmt);
394
395 /* Add default sort criteria */
396 parsesort("tdev,pid");
397 SIMPLEQ_FOREACH(vent, &sortlist, next) {
398 if (vent->var->flag & LWP || vent->var->type == UNSPECIFIED)
399 warnx("Cannot sort on %s, sort key ignored",
400 vent->var->name);
401 }
402
403 /*
404 * scan requested variables, noting what structures are needed.
405 */
406 scanvars();
407
408 /*
409 * select procs
410 */
411 if (!(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
412 err(1, "%s", kvm_geterr(kd));
413 if (nentries == 0) {
414 printheader();
415 return 1;
416 }
417 /*
418 * sort proc list
419 */
420 qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
421 /*
422 * For each proc, call each variable output function in
423 * "setwidth" mode to determine the widest element of
424 * the column.
425 */
426
427 for (i = 0; i < nentries; i++) {
428 struct kinfo_proc2 *ki = &kinfo[i];
429
430 if (xflg == 0 && (ki->p_tdev == (uint32_t)NODEV ||
431 (ki->p_flag & P_CONTROLT) == 0))
432 continue;
433
434 kl = kvm_getlwps(kd, ki->p_pid, ki->p_paddr,
435 sizeof(struct kinfo_lwp), &nlwps);
436 if (kl == 0)
437 nlwps = 0;
438 if (showlwps == 0) {
439 l = pick_representative_lwp(ki, kl, nlwps);
440 SIMPLEQ_FOREACH(vent, &displaylist, next)
441 OUTPUT(vent, ki, l, WIDTHMODE);
442 } else {
443 /* The printing is done with the loops
444 * reversed, but here we don't need that,
445 * and this improves the code locality a bit.
446 */
447 SIMPLEQ_FOREACH(vent, &displaylist, next)
448 for (j = 0; j < nlwps; j++)
449 OUTPUT(vent, ki, &kl[j], WIDTHMODE);
450 }
451 }
452 /*
453 * Print header - AFTER determining process field widths.
454 * printheader() also adds up the total width of all
455 * fields the first time it's called.
456 */
457 printheader();
458 /*
459 * For each proc, call each variable output function in
460 * print mode.
461 */
462 for (i = lineno = 0; i < nentries; i++) {
463 struct kinfo_proc2 *ki = &kinfo[i];
464
465 if (xflg == 0 && (ki->p_tdev == (uint32_t)NODEV ||
466 (ki->p_flag & P_CONTROLT ) == 0))
467 continue;
468 kl = kvm_getlwps(kd, ki->p_pid, (u_long)ki->p_paddr,
469 sizeof(struct kinfo_lwp), &nlwps);
470 if (kl == 0)
471 nlwps = 0;
472 if (showlwps == 0) {
473 l = pick_representative_lwp(ki, kl, nlwps);
474 SIMPLEQ_FOREACH(vent, &displaylist, next) {
475 OUTPUT(vent, ki, l, PRINTMODE);
476 if (SIMPLEQ_NEXT(vent, next) != NULL)
477 (void)putchar(' ');
478 }
479 (void)putchar('\n');
480 if (prtheader && lineno++ == prtheader - 4) {
481 (void)putchar('\n');
482 printheader();
483 lineno = 0;
484 }
485 } else {
486 for (j = 0; j < nlwps; j++) {
487 SIMPLEQ_FOREACH(vent, &displaylist, next) {
488 OUTPUT(vent, ki, &kl[j], PRINTMODE);
489 if (SIMPLEQ_NEXT(vent, next) != NULL)
490 (void)putchar(' ');
491 }
492 (void)putchar('\n');
493 if (prtheader && lineno++ == prtheader - 4) {
494 (void)putchar('\n');
495 printheader();
496 lineno = 0;
497 }
498 }
499 }
500 }
501 return eval;
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", ki->p_pid);
559 return kl;
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