xref: /netbsd-src/bin/ps/ps.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: ps.c,v 1.55 2004/10/29 19:53:29 dsl 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.55 2004/10/29 19:53:29 dsl 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 (*ttname != '/')
273 				(void)snprintf(ttypath = pathbuf,
274 				    sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
275 			else
276 				ttypath = ttname;
277 			what = KERN_PROC_TTY;
278 			if (flag == 0) {
279 				if (stat(ttypath, &sb) == -1)
280 					err(1, "%s", ttypath);
281 				if (!S_ISCHR(sb.st_mode))
282 					errx(1, "%s: not a terminal", ttypath);
283 				flag = sb.st_rdev;
284 			}
285 			break;
286 		}
287 		case 'U':
288 			if (*optarg != '\0') {
289 				struct passwd *pw;
290 				char *ep;
291 
292 				what = KERN_PROC_UID;
293 				pw = getpwnam(optarg);
294 				if (pw == NULL) {
295 					errno = 0;
296 					flag = strtoul(optarg, &ep, 10);
297 					if (errno)
298 						err(1, "%s", optarg);
299 					if (*ep != '\0')
300 						errx(1, "%s: illegal user name",
301 						    optarg);
302 				} else
303 					flag = pw->pw_uid;
304 			}
305 			break;
306 		case 'u':
307 			parsefmt(ufmt);
308 			parsesort("%cpu");
309 			fmt = 1;
310 			ufmt[0] = '\0';
311 			break;
312 		case 'v':
313 			parsefmt(vfmt);
314 			parsesort("vsz");
315 			fmt = 1;
316 			vfmt[0] = '\0';
317 			break;
318 		case 'W':
319 			swapf = optarg;
320 			break;
321 		case 'w':
322 			if (wflag)
323 				termwidth = UNLIMITED;
324 			else if (termwidth < 131)
325 				termwidth = 131;
326 			wflag++;
327 			break;
328 		case 'x':
329 			xflg = 1;
330 			break;
331 		case '?':
332 		default:
333 			usage();
334 		}
335 	argc -= optind;
336 	argv += optind;
337 
338 #define	BACKWARD_COMPATIBILITY
339 #ifdef	BACKWARD_COMPATIBILITY
340 	if (*argv) {
341 		nlistf = *argv;
342 		if (*++argv) {
343 			memf = *argv;
344 			if (*++argv)
345 				swapf = *argv;
346 		}
347 	}
348 #endif
349 
350 	if (memf == NULL) {
351 		kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
352 		donlist_sysctl();
353 	} else
354 		kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
355 
356 	if (kd == 0)
357 		errx(1, "%s", errbuf);
358 
359 	if (!fmt)
360 		parsefmt(dfmt);
361 
362 	/* Add default sort criteria */
363 	parsesort("tdev,pid");
364 	for (vent = sorthead; vent; vent = vent->next) {
365 		if (vent->var->flag & LWP || vent->var->type == UNSPECIFIED)
366 			warnx("Cannot sort on %s, sort key ignored\n",
367 				vent->var->name);
368 	}
369 
370 	/*
371 	 * scan requested variables, noting what structures are needed.
372 	 */
373 	scanvars();
374 
375 	/*
376 	 * select procs
377 	 */
378 	if (!(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
379 		err(1, "%s", kvm_geterr(kd));
380 	if (nentries == 0) {
381 		printheader();
382 		exit(1);
383 	}
384 	/*
385 	 * sort proc list
386 	 */
387 	qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
388 	/*
389 	 * For each proc, call each variable output function in
390 	 * "setwidth" mode to determine the widest element of
391 	 * the column.
392 	 */
393 	if (mode == PRINTMODE)
394 		for (i = 0; i < nentries; i++) {
395 			struct kinfo_proc2 *ki = &kinfo[i];
396 
397 			if (xflg == 0 && (ki->p_tdev == NODEV ||
398 			    (ki->p_flag & P_CONTROLT) == 0))
399 				continue;
400 
401 			kl = kvm_getlwps(kd, ki->p_pid, ki->p_paddr,
402 			    sizeof(struct kinfo_lwp), &nlwps);
403 			if (kl == 0)
404 				nlwps = 0;
405 			if (showlwps == 0) {
406 				l = pick_representative_lwp(ki, kl, nlwps);
407 				for (vent = vhead; vent; vent = vent->next)
408 					OUTPUT(vent, ki, l, WIDTHMODE);
409 			} else {
410 				/* The printing is done with the loops
411 				 * reversed, but here we don't need that,
412 				 * and this improves the code locality a bit.
413 				 */
414 				for (vent = vhead; vent; vent = vent->next)
415 					for (j = 0; j < nlwps; j++)
416 						OUTPUT(vent, ki, &kl[j],
417 						    WIDTHMODE);
418 			}
419 		}
420 	/*
421 	 * Print header - AFTER determining process field widths.
422 	 * printheader() also adds up the total width of all
423 	 * fields the first time it's called.
424 	 */
425 	printheader();
426 	/*
427 	 * For each proc, call each variable output function in
428 	 * print mode.
429 	 */
430 	for (i = lineno = 0; i < nentries; i++) {
431 		struct kinfo_proc2 *ki = &kinfo[i];
432 
433 		if (xflg == 0 && (ki->p_tdev == NODEV ||
434 		    (ki->p_flag & P_CONTROLT ) == 0))
435 			continue;
436 		kl = kvm_getlwps(kd, ki->p_pid, (u_long)ki->p_paddr,
437 		    sizeof(struct kinfo_lwp), &nlwps);
438 		if (kl == 0)
439 			nlwps = 0;
440 		if (showlwps == 0) {
441 			l = pick_representative_lwp(ki, kl, nlwps);
442 			for (vent = vhead; vent; vent = vent->next) {
443 				OUTPUT(vent, ki, l, mode);
444 				if (vent->next != NULL)
445 					(void)putchar(' ');
446 			}
447 			(void)putchar('\n');
448 			if (prtheader && lineno++ == prtheader - 4) {
449 				(void)putchar('\n');
450 				printheader();
451 				lineno = 0;
452 			}
453 		} else {
454 			for (j = 0; j < nlwps; j++) {
455 				for (vent = vhead; vent; vent = vent->next) {
456 					OUTPUT(vent, ki, &kl[j], mode);
457 					if (vent->next != NULL)
458 						(void)putchar(' ');
459 				}
460 				(void)putchar('\n');
461 				if (prtheader && lineno++ == prtheader - 4) {
462 					(void)putchar('\n');
463 					printheader();
464 					lineno = 0;
465 				}
466 			}
467 		}
468 	}
469 	exit(eval);
470 	/* NOTREACHED */
471 }
472 
473 static struct kinfo_lwp *
474 pick_representative_lwp(struct kinfo_proc2 *ki, struct kinfo_lwp *kl, int nlwps)
475 {
476 	int i, onproc, running, sleeping, stopped, suspended;
477 	static struct kinfo_lwp zero_lwp;
478 
479 	if (kl == 0)
480 		return &zero_lwp;
481 
482 	/* Trivial case: only one LWP */
483 	if (nlwps == 1)
484 		return kl;
485 
486 	switch (ki->p_realstat) {
487 	case SSTOP:
488 	case SACTIVE:
489 		/* Pick the most live LWP */
490 		onproc = running = sleeping = stopped = suspended = -1;
491 		for (i = 0; i < nlwps; i++) {
492 			switch (kl[i].l_stat) {
493 			case LSONPROC:
494 				onproc = i;
495 				break;
496 			case LSRUN:
497 				running = i;
498 				break;
499 			case LSSLEEP:
500 				sleeping = i;
501 				break;
502 			case LSSTOP:
503 				stopped = i;
504 				break;
505 			case LSSUSPENDED:
506 				suspended = i;
507 				break;
508 			}
509 		}
510 		if (onproc != -1)
511 			return &kl[onproc];
512 		if (running != -1)
513 			return &kl[running];
514 		if (sleeping != -1)
515 			return &kl[sleeping];
516 		if (stopped != -1)
517 			return &kl[stopped];
518 		if (suspended != -1)
519 			return &kl[suspended];
520 		break;
521 	case SZOMB:
522 		/* First will do */
523 		return kl;
524 		break;
525 	}
526 	/* Error condition! */
527 	warnx("Inconsistent LWP state for process %d\n", ki->p_pid);
528 	return kl;
529 }
530 
531 
532 static struct kinfo_proc2 *
533 getkinfo_kvm(kvm_t *kdp, int what, int flag, int *nentriesp)
534 {
535 
536 	return (kvm_getproc2(kdp, what, flag, sizeof(struct kinfo_proc2),
537 	    nentriesp));
538 }
539 
540 static void
541 scanvars(void)
542 {
543 	struct varent *vent;
544 	VAR *v;
545 
546 	for (vent = vhead; vent; vent = vent->next) {
547 		v = vent->var;
548 		if (v->flag & COMM) {
549 			needcomm = 1;
550 			break;
551 		}
552 	}
553 }
554 
555 static int
556 pscomp(const void *a, const void *b)
557 {
558 	struct kinfo_proc2 *ka = (struct kinfo_proc2 *)a;
559 	struct kinfo_proc2 *kb = (struct kinfo_proc2 *)b;
560 
561 	int i;
562 	int64_t i64;
563 	VAR *v;
564 	struct varent *ve;
565 	sigset_t *sa, *sb;
566 
567 #define	V_SIZE(k) (k->p_vm_dsize + k->p_vm_ssize + k->p_vm_tsize)
568 #define	RDIFF_N(t, n) \
569 	if (((t *)((char *)ka + v->off))[n] > ((t *)((char *)kb + v->off))[n]) \
570 		return 1; \
571 	if (((t *)((char *)ka + v->off))[n] < ((t *)((char *)kb + v->off))[n]) \
572 		return -1;
573 
574 #define	RDIFF(type) RDIFF_N(type, 0); continue
575 
576 	for (ve = sorthead; ve != NULL; ve = ve->next) {
577 		v = ve->var;
578 		if (v->flag & LWP)
579 			/* LWP structure not available (yet) */
580 			continue;
581 		/* Sort on pvar() fields, + a few others */
582 		switch (v->type) {
583 		case CHAR:
584 			RDIFF(char);
585 		case UCHAR:
586 			RDIFF(u_char);
587 		case SHORT:
588 			RDIFF(short);
589 		case USHORT:
590 			RDIFF(ushort);
591 		case INT:
592 			RDIFF(int);
593 		case UINT:
594 			RDIFF(uint);
595 		case LONG:
596 			RDIFF(long);
597 		case ULONG:
598 			RDIFF(ulong);
599 		case INT32:
600 			RDIFF(int32_t);
601 		case UINT32:
602 			RDIFF(uint32_t);
603 		case SIGLIST:
604 			sa = (void *)((char *)a + v->off);
605 			sb = (void *)((char *)b + v->off);
606 			i = 0;
607 			do {
608 				if (sa->__bits[i] > sb->__bits[i])
609 					return 1;
610 				if (sa->__bits[i] < sb->__bits[i])
611 					return -1;
612 				i++;
613 			} while (i < sizeof sa->__bits / sizeof sa->__bits[0]);
614 			continue;
615 		case INT64:
616 			RDIFF(int64_t);
617 		case KPTR:
618 		case KPTR24:
619 		case UINT64:
620 			RDIFF(uint64_t);
621 		case TIMEVAL:
622 			/* compare xxx_sec then xxx_usec */
623 			RDIFF_N(uint32_t, 0);
624 			RDIFF_N(uint32_t, 1);
625 			continue;
626 		case CPUTIME:
627 			i64 = ka->p_rtime_sec * 1000000 + ka->p_rtime_usec;
628 			i64 -= kb->p_rtime_sec * 1000000 + kb->p_rtime_usec;
629 			if (sumrusage) {
630 				i64 += ka->p_uctime_sec * 1000000
631 				    + ka->p_uctime_usec;
632 				i64 -= kb->p_uctime_sec * 1000000
633 				    + kb->p_uctime_usec;
634 			}
635 			if (i64 != 0)
636 				return i64 > 0 ? 1 : -1;
637 			continue;
638 		case PCPU:
639 			i = getpcpu(kb) - getpcpu(ka);
640 			if (i != 0)
641 				return i;
642 			continue;
643 		case VSIZE:
644 			i = V_SIZE(kb) - V_SIZE(ka);
645 			if (i != 0)
646 				return i;
647 			continue;
648 
649 		default:
650 			/* Ignore everything else */
651 			break;
652 		}
653 	}
654 	return 0;
655 
656 #undef VSIZE
657 }
658 
659 /*
660  * ICK (all for getopt), would rather hide the ugliness
661  * here than taint the main code.
662  *
663  *  ps foo -> ps -foo
664  *  ps 34 -> ps -p34
665  *
666  * The old convention that 't' with no trailing tty arg means the user's
667  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
668  * feature is available with the option 'T', which takes no argument.
669  */
670 static char *
671 kludge_oldps_options(char *s)
672 {
673 	size_t len;
674 	char *newopts, *ns, *cp;
675 
676 	len = strlen(s);
677 	if ((newopts = ns = malloc(len + 3)) == NULL)
678 		err(1, NULL);
679 	/*
680 	 * options begin with '-'
681 	 */
682 	if (*s != '-')
683 		*ns++ = '-';	/* add option flag */
684 	/*
685 	 * gaze to end of argv[1]
686 	 */
687 	cp = s + len - 1;
688 	/*
689 	 * if the last letter is a 't' flag and there are no other option
690 	 * characters that take arguments (eg U, p, o) in the option
691 	 * string and the option string doesn't start with a '-' then
692 	 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
693 	 */
694 	if (*cp == 't' && *s != '-' && strpbrk(s, ARGOPTS) == NULL)
695 		*cp = 'T';
696 	else {
697 		/*
698 		 * otherwise check for trailing number, which *may* be a
699 		 * pid.
700 		 */
701 		while (cp >= s && isdigit((unsigned char)*cp))
702 			--cp;
703 	}
704 	cp++;
705 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
706 	ns += cp - s;
707 	/*
708 	 * if there's a trailing number, and not a preceding 'p' (pid) or
709 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
710 	 */
711 	if (isdigit((unsigned char)*cp) &&
712 	    (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
713 	     (cp - 1 == s || cp[-2] != 't'))))
714 		*ns++ = 'p';
715 	/* and append the number */
716 	(void)strcpy(ns, cp);		/* XXX strcpy is safe here */
717 
718 	return (newopts);
719 }
720 
721 static void
722 usage(void)
723 {
724 
725 	(void)fprintf(stderr,
726 	    "usage:\t%s\n\t   %s\n\t%s\n",
727 	    "ps [-acCehjlmrsSTuvwx] [-k key] [-O|o fmt] [-p pid] [-t tty]",
728 	    "[-M core] [-N system] [-W swap] [-U username]",
729 	    "ps [-L]");
730 	exit(1);
731 	/* NOTREACHED */
732 }
733