xref: /netbsd-src/bin/ps/ps.c (revision 1c9b56c830954ccf3b57004ac65562e3d6afacf6)
1 /*	$NetBSD: ps.c,v 1.57 2005/02/11 18:26:18 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2000 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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*
40  * Copyright (c) 1990, 1993, 1994
41  *	The Regents of the University of California.  All rights reserved.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. Neither the name of the University nor the names of its contributors
52  *    may be used to endorse or promote products derived from this software
53  *    without specific prior written permission.
54  *
55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65  * SUCH DAMAGE.
66  */
67 
68 #include <sys/cdefs.h>
69 #ifndef lint
70 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\n\
71 	The Regents of the University of California.  All rights reserved.\n");
72 #endif /* not lint */
73 
74 #ifndef lint
75 #if 0
76 static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
77 #else
78 __RCSID("$NetBSD: ps.c,v 1.57 2005/02/11 18:26:18 christos Exp $");
79 #endif
80 #endif /* not lint */
81 
82 #include <sys/param.h>
83 #include <sys/user.h>
84 #include <sys/time.h>
85 #include <sys/resource.h>
86 #include <sys/lwp.h>
87 #include <sys/proc.h>
88 #include <sys/stat.h>
89 #include <sys/ioctl.h>
90 #include <sys/sysctl.h>
91 
92 #include <stddef.h>
93 #include <ctype.h>
94 #include <err.h>
95 #include <errno.h>
96 #include <fcntl.h>
97 #include <kvm.h>
98 #include <limits.h>
99 #include <nlist.h>
100 #include <paths.h>
101 #include <pwd.h>
102 #include <stdio.h>
103 #include <stdlib.h>
104 #include <string.h>
105 #include <unistd.h>
106 
107 #include "ps.h"
108 
109 /*
110  * ARGOPTS must contain all option characters that take arguments
111  * (except for 't'!) - it is used in kludge_oldps_options()
112  */
113 #define	GETOPTSTR	"acCeghjk:LlM:mN:O:o:p:rSsTt:U:uvW:wx"
114 #define	ARGOPTS		"kMNOopUW"
115 
116 struct kinfo_proc2 *kinfo;
117 struct varent *vhead, *sorthead;
118 
119 int	eval;			/* exit value */
120 int	rawcpu;			/* -C */
121 int	sumrusage;		/* -S */
122 int	termwidth;		/* width of screen (0 == infinity) */
123 int	totwidth;		/* calculated width of requested variables */
124 
125 int	needcomm, needenv, commandonly;
126 uid_t	myuid;
127 
128 static struct kinfo_lwp
129 		*pick_representative_lwp(struct kinfo_proc2 *,
130 		    struct kinfo_lwp *, int);
131 static struct kinfo_proc2
132 		*getkinfo_kvm(kvm_t *, int, int, int *);
133 static char	*kludge_oldps_options(char *);
134 static int	 pscomp(const void *, const void *);
135 static void	 scanvars(void);
136 static void	 usage(void);
137 int		 main(int, char *[]);
138 
139 char dfmt[] = "pid tt state time command";
140 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
141 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
142 char   o1[] = "pid";
143 char   o2[] = "tt state time command";
144 char sfmt[] = "uid pid ppid cpu lid nlwp pri nice vsz rss wchan lstate tt "
145 		"time command";
146 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
147 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
148 
149 kvm_t *kd;
150 
151 int
152 main(int argc, char *argv[])
153 {
154 	struct varent *vent;
155 	struct winsize ws;
156 	struct kinfo_lwp *kl, *l;
157 	int ch, flag, i, j, fmt, lineno, nentries, nlwps;
158 	int prtheader, wflag, what, xflg, mode, showlwps;
159 	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
160 	char *ttname;
161 
162 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
163 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
164 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
165 	     ws.ws_col == 0)
166 		termwidth = 79;
167 	else
168 		termwidth = ws.ws_col - 1;
169 
170 	if (argc > 1)
171 		argv[1] = kludge_oldps_options(argv[1]);
172 
173 	fmt = prtheader = wflag = xflg = showlwps = 0;
174 	what = KERN_PROC_UID;
175 	flag = myuid = getuid();
176 	memf = nlistf = swapf = NULL;
177 	mode = PRINTMODE;
178 	while ((ch = getopt(argc, argv, GETOPTSTR)) != -1)
179 		switch((char)ch) {
180 		case 'a':
181 			what = KERN_PROC_ALL;
182 			flag = 0;
183 			break;
184 		case 'c':
185 			commandonly = 1;
186 			break;
187 		case 'e':			/* XXX set ufmt */
188 			needenv = 1;
189 			break;
190 		case 'C':
191 			rawcpu = 1;
192 			break;
193 		case 'g':
194 			break;			/* no-op */
195 		case 'h':
196 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
197 			break;
198 		case 'j':
199 			parsefmt(jfmt);
200 			fmt = 1;
201 			jfmt[0] = '\0';
202 			break;
203 		case 'k':
204 			parsesort(optarg);
205 			break;
206 		case 'K':
207 			break;			/* no-op - was dontuseprocfs */
208 		case 'L':
209 			showkey();
210 			exit(0);
211 			/* NOTREACHED */
212 		case 'l':
213 			parsefmt(lfmt);
214 			fmt = 1;
215 			lfmt[0] = '\0';
216 			break;
217 		case 'M':
218 			memf = optarg;
219 			break;
220 		case 'm':
221 			parsesort("vsz");
222 			break;
223 		case 'N':
224 			nlistf = optarg;
225 			break;
226 		case 'O':
227 			parsefmt(o1);
228 			parsefmt(optarg);
229 			parsefmt(o2);
230 			o1[0] = o2[0] = '\0';
231 			fmt = 1;
232 			break;
233 		case 'o':
234 			parsefmt(optarg);
235 			fmt = 1;
236 			break;
237 		case 'p':
238 			what = KERN_PROC_PID;
239 			flag = atol(optarg);
240 			xflg = 1;
241 			break;
242 		case 'r':
243 			parsesort("%cpu");
244 			break;
245 		case 'S':
246 			sumrusage = 1;
247 			break;
248 		case 's':
249 			/* -L was already taken... */
250 			showlwps = 1;
251 			parsefmt(sfmt);
252 			fmt = 1;
253 			sfmt[0] = '\0';
254 			break;
255 		case 'T':
256 			if ((ttname = ttyname(STDIN_FILENO)) == NULL)
257 				errx(1, "stdin: not a terminal");
258 			goto tty;
259 		case 't':
260 			ttname = optarg;
261 		tty: {
262 			struct stat sb;
263 			char *ttypath, pathbuf[MAXPATHLEN];
264 
265 			flag = 0;
266 			if (strcmp(ttname, "?") == 0)
267 				flag = KERN_PROC_TTY_NODEV;
268 			else if (strcmp(ttname, "-") == 0)
269 				flag = KERN_PROC_TTY_REVOKE;
270 			else if (strcmp(ttname, "co") == 0)
271 				ttypath = _PATH_CONSOLE;
272 			else if (strncmp(ttname, "pts/", 4) == 0 ||
273 				strncmp(ttname, "tty", 3) == 0)
274 				(void)snprintf(ttypath = pathbuf,
275 				    sizeof(pathbuf), "%s%s", _PATH_DEV, ttname);
276 			else if (*ttname != '/')
277 				(void)snprintf(ttypath = pathbuf,
278 				    sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
279 			else
280 				ttypath = ttname;
281 			what = KERN_PROC_TTY;
282 			if (flag == 0) {
283 				if (stat(ttypath, &sb) == -1)
284 					err(1, "%s", ttypath);
285 				if (!S_ISCHR(sb.st_mode))
286 					errx(1, "%s: not a terminal", ttypath);
287 				flag = sb.st_rdev;
288 			}
289 			break;
290 		}
291 		case 'U':
292 			if (*optarg != '\0') {
293 				struct passwd *pw;
294 				char *ep;
295 
296 				what = KERN_PROC_UID;
297 				pw = getpwnam(optarg);
298 				if (pw == NULL) {
299 					errno = 0;
300 					flag = strtoul(optarg, &ep, 10);
301 					if (errno)
302 						err(1, "%s", optarg);
303 					if (*ep != '\0')
304 						errx(1, "%s: illegal user name",
305 						    optarg);
306 				} else
307 					flag = pw->pw_uid;
308 			}
309 			break;
310 		case 'u':
311 			parsefmt(ufmt);
312 			parsesort("%cpu");
313 			fmt = 1;
314 			ufmt[0] = '\0';
315 			break;
316 		case 'v':
317 			parsefmt(vfmt);
318 			parsesort("vsz");
319 			fmt = 1;
320 			vfmt[0] = '\0';
321 			break;
322 		case 'W':
323 			swapf = optarg;
324 			break;
325 		case 'w':
326 			if (wflag)
327 				termwidth = UNLIMITED;
328 			else if (termwidth < 131)
329 				termwidth = 131;
330 			wflag++;
331 			break;
332 		case 'x':
333 			xflg = 1;
334 			break;
335 		case '?':
336 		default:
337 			usage();
338 		}
339 	argc -= optind;
340 	argv += optind;
341 
342 #define	BACKWARD_COMPATIBILITY
343 #ifdef	BACKWARD_COMPATIBILITY
344 	if (*argv) {
345 		nlistf = *argv;
346 		if (*++argv) {
347 			memf = *argv;
348 			if (*++argv)
349 				swapf = *argv;
350 		}
351 	}
352 #endif
353 
354 	if (memf == NULL) {
355 		kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
356 		donlist_sysctl();
357 	} else
358 		kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
359 
360 	if (kd == 0)
361 		errx(1, "%s", errbuf);
362 
363 	if (!fmt)
364 		parsefmt(dfmt);
365 
366 	/* Add default sort criteria */
367 	parsesort("tdev,pid");
368 	for (vent = sorthead; vent; vent = vent->next) {
369 		if (vent->var->flag & LWP || vent->var->type == UNSPECIFIED)
370 			warnx("Cannot sort on %s, sort key ignored\n",
371 				vent->var->name);
372 	}
373 
374 	/*
375 	 * scan requested variables, noting what structures are needed.
376 	 */
377 	scanvars();
378 
379 	/*
380 	 * select procs
381 	 */
382 	if (!(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
383 		err(1, "%s", kvm_geterr(kd));
384 	if (nentries == 0) {
385 		printheader();
386 		exit(1);
387 	}
388 	/*
389 	 * sort proc list
390 	 */
391 	qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
392 	/*
393 	 * For each proc, call each variable output function in
394 	 * "setwidth" mode to determine the widest element of
395 	 * the column.
396 	 */
397 	if (mode == PRINTMODE)
398 		for (i = 0; i < nentries; i++) {
399 			struct kinfo_proc2 *ki = &kinfo[i];
400 
401 			if (xflg == 0 && (ki->p_tdev == NODEV ||
402 			    (ki->p_flag & P_CONTROLT) == 0))
403 				continue;
404 
405 			kl = kvm_getlwps(kd, ki->p_pid, ki->p_paddr,
406 			    sizeof(struct kinfo_lwp), &nlwps);
407 			if (kl == 0)
408 				nlwps = 0;
409 			if (showlwps == 0) {
410 				l = pick_representative_lwp(ki, kl, nlwps);
411 				for (vent = vhead; vent; vent = vent->next)
412 					OUTPUT(vent, ki, l, WIDTHMODE);
413 			} else {
414 				/* The printing is done with the loops
415 				 * reversed, but here we don't need that,
416 				 * and this improves the code locality a bit.
417 				 */
418 				for (vent = vhead; vent; vent = vent->next)
419 					for (j = 0; j < nlwps; j++)
420 						OUTPUT(vent, ki, &kl[j],
421 						    WIDTHMODE);
422 			}
423 		}
424 	/*
425 	 * Print header - AFTER determining process field widths.
426 	 * printheader() also adds up the total width of all
427 	 * fields the first time it's called.
428 	 */
429 	printheader();
430 	/*
431 	 * For each proc, call each variable output function in
432 	 * print mode.
433 	 */
434 	for (i = lineno = 0; i < nentries; i++) {
435 		struct kinfo_proc2 *ki = &kinfo[i];
436 
437 		if (xflg == 0 && (ki->p_tdev == NODEV ||
438 		    (ki->p_flag & P_CONTROLT ) == 0))
439 			continue;
440 		kl = kvm_getlwps(kd, ki->p_pid, (u_long)ki->p_paddr,
441 		    sizeof(struct kinfo_lwp), &nlwps);
442 		if (kl == 0)
443 			nlwps = 0;
444 		if (showlwps == 0) {
445 			l = pick_representative_lwp(ki, kl, nlwps);
446 			for (vent = vhead; vent; vent = vent->next) {
447 				OUTPUT(vent, ki, l, mode);
448 				if (vent->next != NULL)
449 					(void)putchar(' ');
450 			}
451 			(void)putchar('\n');
452 			if (prtheader && lineno++ == prtheader - 4) {
453 				(void)putchar('\n');
454 				printheader();
455 				lineno = 0;
456 			}
457 		} else {
458 			for (j = 0; j < nlwps; j++) {
459 				for (vent = vhead; vent; vent = vent->next) {
460 					OUTPUT(vent, ki, &kl[j], mode);
461 					if (vent->next != NULL)
462 						(void)putchar(' ');
463 				}
464 				(void)putchar('\n');
465 				if (prtheader && lineno++ == prtheader - 4) {
466 					(void)putchar('\n');
467 					printheader();
468 					lineno = 0;
469 				}
470 			}
471 		}
472 	}
473 	exit(eval);
474 	/* NOTREACHED */
475 }
476 
477 static struct kinfo_lwp *
478 pick_representative_lwp(struct kinfo_proc2 *ki, struct kinfo_lwp *kl, int nlwps)
479 {
480 	int i, onproc, running, sleeping, stopped, suspended;
481 	static struct kinfo_lwp zero_lwp;
482 
483 	if (kl == 0)
484 		return &zero_lwp;
485 
486 	/* Trivial case: only one LWP */
487 	if (nlwps == 1)
488 		return kl;
489 
490 	switch (ki->p_realstat) {
491 	case SSTOP:
492 	case SACTIVE:
493 		/* Pick the most live LWP */
494 		onproc = running = sleeping = stopped = suspended = -1;
495 		for (i = 0; i < nlwps; i++) {
496 			switch (kl[i].l_stat) {
497 			case LSONPROC:
498 				onproc = i;
499 				break;
500 			case LSRUN:
501 				running = i;
502 				break;
503 			case LSSLEEP:
504 				sleeping = i;
505 				break;
506 			case LSSTOP:
507 				stopped = i;
508 				break;
509 			case LSSUSPENDED:
510 				suspended = i;
511 				break;
512 			}
513 		}
514 		if (onproc != -1)
515 			return &kl[onproc];
516 		if (running != -1)
517 			return &kl[running];
518 		if (sleeping != -1)
519 			return &kl[sleeping];
520 		if (stopped != -1)
521 			return &kl[stopped];
522 		if (suspended != -1)
523 			return &kl[suspended];
524 		break;
525 	case SZOMB:
526 		/* First will do */
527 		return kl;
528 		break;
529 	}
530 	/* Error condition! */
531 	warnx("Inconsistent LWP state for process %d\n", ki->p_pid);
532 	return kl;
533 }
534 
535 
536 static struct kinfo_proc2 *
537 getkinfo_kvm(kvm_t *kdp, int what, int flag, int *nentriesp)
538 {
539 
540 	return (kvm_getproc2(kdp, what, flag, sizeof(struct kinfo_proc2),
541 	    nentriesp));
542 }
543 
544 static void
545 scanvars(void)
546 {
547 	struct varent *vent;
548 	VAR *v;
549 
550 	for (vent = vhead; vent; vent = vent->next) {
551 		v = vent->var;
552 		if (v->flag & COMM) {
553 			needcomm = 1;
554 			break;
555 		}
556 	}
557 }
558 
559 static int
560 pscomp(const void *a, const void *b)
561 {
562 	struct kinfo_proc2 *ka = (struct kinfo_proc2 *)a;
563 	struct kinfo_proc2 *kb = (struct kinfo_proc2 *)b;
564 
565 	int i;
566 	int64_t i64;
567 	VAR *v;
568 	struct varent *ve;
569 	sigset_t *sa, *sb;
570 
571 #define	V_SIZE(k) (k->p_vm_dsize + k->p_vm_ssize + k->p_vm_tsize)
572 #define	RDIFF_N(t, n) \
573 	if (((t *)((char *)ka + v->off))[n] > ((t *)((char *)kb + v->off))[n]) \
574 		return 1; \
575 	if (((t *)((char *)ka + v->off))[n] < ((t *)((char *)kb + v->off))[n]) \
576 		return -1;
577 
578 #define	RDIFF(type) RDIFF_N(type, 0); continue
579 
580 	for (ve = sorthead; ve != NULL; ve = ve->next) {
581 		v = ve->var;
582 		if (v->flag & LWP)
583 			/* LWP structure not available (yet) */
584 			continue;
585 		/* Sort on pvar() fields, + a few others */
586 		switch (v->type) {
587 		case CHAR:
588 			RDIFF(char);
589 		case UCHAR:
590 			RDIFF(u_char);
591 		case SHORT:
592 			RDIFF(short);
593 		case USHORT:
594 			RDIFF(ushort);
595 		case INT:
596 			RDIFF(int);
597 		case UINT:
598 			RDIFF(uint);
599 		case LONG:
600 			RDIFF(long);
601 		case ULONG:
602 			RDIFF(ulong);
603 		case INT32:
604 			RDIFF(int32_t);
605 		case UINT32:
606 			RDIFF(uint32_t);
607 		case SIGLIST:
608 			sa = (void *)((char *)a + v->off);
609 			sb = (void *)((char *)b + v->off);
610 			i = 0;
611 			do {
612 				if (sa->__bits[i] > sb->__bits[i])
613 					return 1;
614 				if (sa->__bits[i] < sb->__bits[i])
615 					return -1;
616 				i++;
617 			} while (i < sizeof sa->__bits / sizeof sa->__bits[0]);
618 			continue;
619 		case INT64:
620 			RDIFF(int64_t);
621 		case KPTR:
622 		case KPTR24:
623 		case UINT64:
624 			RDIFF(uint64_t);
625 		case TIMEVAL:
626 			/* compare xxx_sec then xxx_usec */
627 			RDIFF_N(uint32_t, 0);
628 			RDIFF_N(uint32_t, 1);
629 			continue;
630 		case CPUTIME:
631 			i64 = ka->p_rtime_sec * 1000000 + ka->p_rtime_usec;
632 			i64 -= kb->p_rtime_sec * 1000000 + kb->p_rtime_usec;
633 			if (sumrusage) {
634 				i64 += ka->p_uctime_sec * 1000000
635 				    + ka->p_uctime_usec;
636 				i64 -= kb->p_uctime_sec * 1000000
637 				    + kb->p_uctime_usec;
638 			}
639 			if (i64 != 0)
640 				return i64 > 0 ? 1 : -1;
641 			continue;
642 		case PCPU:
643 			i = getpcpu(kb) - getpcpu(ka);
644 			if (i != 0)
645 				return i;
646 			continue;
647 		case VSIZE:
648 			i = V_SIZE(kb) - V_SIZE(ka);
649 			if (i != 0)
650 				return i;
651 			continue;
652 
653 		default:
654 			/* Ignore everything else */
655 			break;
656 		}
657 	}
658 	return 0;
659 
660 #undef VSIZE
661 }
662 
663 /*
664  * ICK (all for getopt), would rather hide the ugliness
665  * here than taint the main code.
666  *
667  *  ps foo -> ps -foo
668  *  ps 34 -> ps -p34
669  *
670  * The old convention that 't' with no trailing tty arg means the user's
671  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
672  * feature is available with the option 'T', which takes no argument.
673  */
674 static char *
675 kludge_oldps_options(char *s)
676 {
677 	size_t len;
678 	char *newopts, *ns, *cp;
679 
680 	len = strlen(s);
681 	if ((newopts = ns = malloc(len + 3)) == NULL)
682 		err(1, NULL);
683 	/*
684 	 * options begin with '-'
685 	 */
686 	if (*s != '-')
687 		*ns++ = '-';	/* add option flag */
688 	/*
689 	 * gaze to end of argv[1]
690 	 */
691 	cp = s + len - 1;
692 	/*
693 	 * if the last letter is a 't' flag and there are no other option
694 	 * characters that take arguments (eg U, p, o) in the option
695 	 * string and the option string doesn't start with a '-' then
696 	 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
697 	 */
698 	if (*cp == 't' && *s != '-' && strpbrk(s, ARGOPTS) == NULL)
699 		*cp = 'T';
700 	else {
701 		/*
702 		 * otherwise check for trailing number, which *may* be a
703 		 * pid.
704 		 */
705 		while (cp >= s && isdigit((unsigned char)*cp))
706 			--cp;
707 	}
708 	cp++;
709 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
710 	ns += cp - s;
711 	/*
712 	 * if there's a trailing number, and not a preceding 'p' (pid) or
713 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
714 	 */
715 	if (isdigit((unsigned char)*cp) &&
716 	    (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
717 	    cp[-1] != '/' && (cp - 1 == s || cp[-2] != 't'))))
718 		*ns++ = 'p';
719 	/* and append the number */
720 	(void)strcpy(ns, cp);		/* XXX strcpy is safe here */
721 
722 	return (newopts);
723 }
724 
725 static void
726 usage(void)
727 {
728 
729 	(void)fprintf(stderr,
730 	    "usage:\t%s\n\t   %s\n\t%s\n",
731 	    "ps [-acCehjlmrsSTuvwx] [-k key] [-O|o fmt] [-p pid] [-t tty]",
732 	    "[-M core] [-N system] [-W swap] [-U username]",
733 	    "ps [-L]");
734 	exit(1);
735 	/* NOTREACHED */
736 }
737