xref: /dragonfly/bin/ps/ps.c (revision 8accc937)
1 /*-
2  * Copyright (c) 1990, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1990, 1993, 1994 The Regents of the University of California.  All rights reserved.
34  * @(#)ps.c	8.4 (Berkeley) 4/2/94
35  * $FreeBSD: src/bin/ps/ps.c,v 1.30.2.6 2002/07/04 08:30:37 sobomax Exp $
36  */
37 
38 #include <sys/user.h>
39 #include <sys/param.h>
40 #include <sys/time.h>
41 #include <sys/queue.h>
42 #include <sys/resource.h>
43 #include <sys/stat.h>
44 #include <sys/ioctl.h>
45 #include <sys/sysctl.h>
46 #include <sys/mount.h>
47 
48 #include <ctype.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <kvm.h>
53 #include <limits.h>
54 #include <locale.h>
55 #include <nlist.h>
56 #include <paths.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61 #include <pwd.h>
62 #include <utmp.h>
63 
64 #include "ps.h"
65 
66 #define SEP ", \t"		/* username separators */
67 
68 #define KHSIZE	2048
69 #define KHMASK	(KHSIZE - 1)
70 
71 KINFO *KInfo;
72 KINFO **KSort;
73 struct varent *vhead, *vtail;
74 
75 int	eval;			/* exit value */
76 int	cflag;			/* -c */
77 int	rawcpu;			/* -C */
78 int	sumrusage;		/* -S */
79 int	termwidth;		/* width of screen (0 == infinity) */
80 int	totwidth;		/* calculated width of requested variables */
81 int	numcpus;		/* hw.ncpu */
82 
83 static int needuser, needcomm, needenv;
84 #if defined(LAZY_PS)
85 static int forceuread=0;
86 #define PS_ARGS	"aCcefgHhjLlM:mN:O:o:p:rRSTt:U:uvwx"
87 #else
88 static int forceuread=1;
89 #define PS_ARGS	"aCcegHhjLlM:mN:O:o:p:rRSTt:U:uvwx"
90 #endif
91 
92 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
93 
94 static const char *getfmt (char **(*)(kvm_t *, const struct kinfo_proc *, int),
95 		    KINFO *, char *, int);
96 static char	*kludge_oldps_options (char *);
97 static int	 pscomp (const void *, const void *);
98 static void	 dochain (KINFO **ksort, int nentries);
99 static void	 saveuser (KINFO *);
100 static void	 scanvars (void);
101 static void	 dynsizevars (KINFO *);
102 static void	 sizevars (void);
103 static int	 check_procfs(void);
104 static void	 usage (void);
105 static uid_t	*getuids(const char *, int *);
106 
107 struct timeval btime;
108 
109 static char dfmt[] = "pid tt state time command";
110 static char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
111 static char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
112 static char   o1[] = "pid";
113 static char   o2[] = "tt state time command";
114 static char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
115 static char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
116 
117 kvm_t *kd;
118 
119 int
120 main(int argc, char **argv)
121 {
122 	struct kinfo_proc *kp;
123 	struct varent *vent;
124 	struct winsize ws;
125 	dev_t ttydev;
126 	pid_t pid;
127 	uid_t *uids;
128 	int all, ch, flag, i, fmt, ofmt, lineno, nentries, nocludge, dropgid;
129 	int prtheader, wflag, what, xflg, uid, nuids, showtid;
130 	int chainflg;
131 	char errbuf[_POSIX2_LINE_MAX];
132 	const char *cp, *nlistf, *memf;
133 	size_t btime_size = sizeof(struct timeval);
134 	size_t numcpus_size = sizeof(numcpus);
135 
136 	setlocale(LC_ALL, "");
137 
138 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
139 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
140 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
141 	     ws.ws_col == 0)
142 		termwidth = 79;
143 	else
144 		termwidth = ws.ws_col - 1;
145 
146 	/*
147 	 * Don't apply a kludge if the first argument is an option taking an
148 	 * argument
149 	 */
150 	if (argc > 1) {
151 		nocludge = 0;
152 		if (argv[1][0] == '-') {
153 			for (cp = PS_ARGS; *cp != '\0'; cp++) {
154 				if (*cp != ':')
155 					continue;
156 				if (*(cp - 1) == argv[1][1]) {
157 					nocludge = 1;
158 					break;
159 				}
160 			}
161 		}
162 		if (nocludge == 0)
163 			argv[1] = kludge_oldps_options(argv[1]);
164 	}
165 
166 	all = fmt = ofmt = prtheader = wflag = xflg = showtid = 0;
167 	chainflg = 0;
168 	pid = -1;
169 	nuids = 0;
170 	uids = NULL;
171 	ttydev = NODEV;
172 	dropgid = 0;
173 	memf = nlistf = _PATH_DEVNULL;
174 
175 	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
176 		switch((char)ch) {
177 		case 'a':
178 			all = 1;
179 			break;
180 		case 'C':
181 			rawcpu = 1;
182 			break;
183 		case 'c':
184 			cflag = 1;
185 			break;
186 		case 'e':			/* XXX set ufmt */
187 			needenv = 1;
188 			break;
189 		case 'g':
190 			break;			/* no-op */
191 		case 'H':
192 			showtid = KERN_PROC_FLAG_LWP;
193 			break;
194 		case 'h':
195 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
196 			break;
197 		case 'j':
198 			parsefmt(jfmt);
199 			fmt = 1;
200 			jfmt[0] = '\0';
201 			break;
202 		case 'L':
203 			showkey();
204 			exit(0);
205 		case 'l':
206 			parsefmt(lfmt);
207 			fmt = 1;
208 			lfmt[0] = '\0';
209 			break;
210 		case 'M':
211 			memf = optarg;
212 			dropgid = 1;
213 			break;
214 		case 'm':
215 			sortby = SORTMEM;
216 			break;
217 		case 'N':
218 			nlistf = optarg;
219 			dropgid = 1;
220 			break;
221 		case 'O':
222 			parsefmt(o1);
223 			parsefmt(optarg);
224 			parsefmt(o2);
225 			o1[0] = o2[0] = '\0';
226 			fmt = 1;
227 			break;
228 		case 'o':
229 			parsefmt(optarg);
230 			fmt = ofmt = 1;
231 			break;
232 #if defined(LAZY_PS)
233 		case 'f':
234 			if (getuid() == 0 || getgid() == 0)
235 			    forceuread = 1;
236 			break;
237 #endif
238 		case 'p':
239 			pid = atol(optarg);
240 			xflg = 1;
241 			break;
242 		case 'r':
243 			sortby = SORTCPU;
244 			break;
245 		case 'R':
246 			chainflg = 1;
247 			break;
248 		case 'S':
249 			sumrusage = 1;
250 			break;
251 		case 'T':
252 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
253 				errx(1, "stdin: not a terminal");
254 			/* FALLTHROUGH */
255 		case 't': {
256 			struct stat sb;
257 			char pathbuf[PATH_MAX];
258 			const char *ttypath;
259 
260 			if (strcmp(optarg, "co") == 0) {
261 				ttypath = _PATH_CONSOLE;
262 			} else if (*optarg >= '0' && *optarg <= '9') {
263 				snprintf(pathbuf, sizeof(pathbuf),
264 					 "%spts/%s", _PATH_DEV, optarg);
265 				ttypath = pathbuf;
266 			} else if (*optarg != '/') {
267 				snprintf(pathbuf, sizeof(pathbuf),
268 					 "%s%s", _PATH_TTY, optarg);
269 				ttypath = pathbuf;
270 			} else {
271 				ttypath = optarg;
272 			}
273 			if (stat(ttypath, &sb) == -1)
274 				err(1, "%s", ttypath);
275 			if (!S_ISCHR(sb.st_mode))
276 				errx(1, "%s: not a terminal", ttypath);
277 			ttydev = sb.st_rdev;
278 			break;
279 		}
280 		case 'U':
281 			uids = getuids(optarg, &nuids);
282 			xflg++;		/* XXX: intuitive? */
283 			break;
284 		case 'u':
285 			parsefmt(ufmt);
286 			sortby = SORTCPU;
287 			fmt = 1;
288 			ufmt[0] = '\0';
289 			break;
290 		case 'v':
291 			parsefmt(vfmt);
292 			sortby = SORTMEM;
293 			fmt = 1;
294 			vfmt[0] = '\0';
295 			break;
296 		case 'w':
297 			if (wflag)
298 				termwidth = UNLIMITED;
299 			else if (termwidth < 131)
300 				termwidth = 131;
301 			wflag++;
302 			break;
303 		case 'x':
304 			xflg = 1;
305 			break;
306 		case '?':
307 		default:
308 			usage();
309 		}
310 	argc -= optind;
311 	argv += optind;
312 
313 	/*
314 	 * If the user specified ps -e then they want a copy of the process
315 	 * environment kvm_getenvv(3) attempts to open /proc/<pid>/mem.
316 	 * Check to make sure that procfs is mounted on /proc, otherwise
317 	 * print a warning informing the user that output will be incomplete.
318 	 */
319 	if (needenv == 1 && check_procfs() == 0)
320 		warnx("Process environment requires procfs(5)");
321 
322 #define	BACKWARD_COMPATIBILITY
323 #ifdef	BACKWARD_COMPATIBILITY
324 	if (*argv) {
325 		nlistf = *argv;
326 		if (*++argv) {
327 			memf = *argv;
328 		}
329 	}
330 #endif
331 	/*
332 	 * Discard setgid privileges if not the running kernel so that bad
333 	 * guys can't print interesting stuff from kernel memory.
334 	 */
335 	if (dropgid) {
336 		setgid(getgid());
337 		setuid(getuid());
338 	}
339 
340 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
341 	if (kd == NULL)
342 		errx(1, "%s", errbuf);
343 
344 	if (!fmt)
345 		parsefmt(dfmt);
346 
347 	/*
348 	 * Add TID to output format if requested unless user-specific format
349 	 * selected.
350 	 */
351 	if (showtid && !ofmt)
352 		insert_tid_in_fmt();
353 
354 	/* XXX - should be cleaner */
355 	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
356 		if ((uids = malloc(sizeof (*uids))) == NULL)
357 			errx(1, "malloc: %s", strerror(errno));
358 		nuids = 1;
359 		*uids = getuid();
360 	}
361 
362 	/*
363 	 * scan requested variables, noting what structures are needed,
364 	 * and adjusting header widths as appropriate.
365 	 */
366 	scanvars();
367 
368 	/*
369 	 * Get boot time
370 	 */
371 	if (sysctlbyname("kern.boottime", &btime, &btime_size, NULL, 0) < 0) {
372 		perror("sysctl: kern.boottime");
373 		exit(EXIT_FAILURE);
374 	}
375 
376 	/*
377 	 * Get number of cpus
378 	 */
379 	if (sysctlbyname("hw.ncpu", &numcpus, &numcpus_size, NULL, 0) < 0)
380 		numcpus = 1;
381 
382 	/*
383 	 * get proc list
384 	 */
385 	if (nuids == 1) {
386 		what = KERN_PROC_UID;
387 		flag = *uids;
388 	} else if (ttydev != NODEV) {
389 		what = KERN_PROC_TTY;
390 		flag = ttydev;
391 	} else if (pid != -1) {
392 		what = KERN_PROC_PID;
393 		flag = pid;
394 	} else {
395 		what = KERN_PROC_ALL;
396 		flag = 0;
397 	}
398 	what |= showtid;
399 
400 	/*
401 	 * select procs
402 	 */
403 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == NULL)
404 		errx(1, "%s", kvm_geterr(kd));
405 	if ((KInfo = calloc(nentries, sizeof(KINFO))) == NULL)
406 		err(1, NULL);
407 	if ((KSort = malloc(nentries * sizeof(KINFO *))) == NULL)
408 		err(1, NULL);
409 
410 	for (i = 0; i < nentries; ++i) {
411 		KInfo[i].ki_proc = &kp[i];
412 		KInfo[i].ki_indent = -1;
413 		KInfo[i].ki_ctailp = &KInfo[i].ki_cbase;
414 		if (needuser)
415 			saveuser(&KInfo[i]);
416 		dynsizevars(&KInfo[i]);
417 		KSort[i] = &KInfo[i];
418 	}
419 
420 	sizevars();
421 
422 	/*
423 	 * print header
424 	 */
425 	printheader();
426 	if (nentries == 0)
427 		exit(1);
428 	/*
429 	 * sort proc list
430 	 */
431 	qsort(KSort, nentries, sizeof(KINFO *), pscomp);
432 
433 	/*
434 	 * rejigger and indent children, parent(s) and children
435 	 * at each level retain the above sort characteristics.
436 	 */
437 	if (chainflg)
438 		dochain(KSort, nentries);
439 
440 	/*
441 	 * for each proc, call each variable output function.
442 	 */
443 	for (i = lineno = 0; i < nentries; i++) {
444 		if (xflg == 0 && (KI_PROC(KSort[i], tdev) == NODEV ||
445 		    (KI_PROC(KSort[i], flags) & P_CONTROLT ) == 0))
446 			continue;
447 		if (nuids > 1) {
448 			for (uid = 0; uid < nuids; uid++)
449 				if (KI_PROC(KSort[i], uid) ==
450 				    uids[uid])
451 					break;
452 			if (uid == nuids)
453 				continue;
454 		}
455 		STAILQ_FOREACH(vent, &var_head, link) {
456 			(vent->var->oproc)(KSort[i], vent);
457 			if (STAILQ_NEXT(vent, link) != NULL)
458 				putchar(' ');
459 		}
460 		putchar('\n');
461 		if (prtheader && lineno++ == prtheader - 4) {
462 			putchar('\n');
463 			printheader();
464 			lineno = 0;
465 		}
466 	}
467 	free(uids);
468 
469 	exit(eval);
470 }
471 
472 uid_t *
473 getuids(const char *arg, int *nuids)
474 {
475 	char name[UT_NAMESIZE + 1];
476 	struct passwd *pwd;
477 	uid_t *uids, *moreuids;
478 	size_t l;
479 	int alloc;
480 
481 
482 	alloc = 0;
483 	*nuids = 0;
484 	uids = NULL;
485 	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
486 		if (l >= sizeof name) {
487 			warnx("%.*s: name too long", (int)l, arg);
488 			continue;
489 		}
490 		strncpy(name, arg, l);
491 		name[l] = '\0';
492 		if ((pwd = getpwnam(name)) == NULL) {
493 			warnx("%s: no such user", name);
494 			continue;
495 		}
496 		if (*nuids >= alloc) {
497 			alloc = (alloc + 1) << 1;
498 			moreuids = realloc(uids, alloc * sizeof (*uids));
499 			if (moreuids == NULL) {
500 				free(uids);
501 				errx(1, "realloc: %s", strerror(errno));
502 			}
503 			uids = moreuids;
504 		}
505 		uids[(*nuids)++] = pwd->pw_uid;
506 	}
507 	endpwent();
508 
509 	if (!*nuids)
510 		errx(1, "No users specified");
511 
512 	return uids;
513 }
514 
515 static void
516 scanvars(void)
517 {
518 	struct varent *vent;
519 	const VAR *v;
520 
521 	STAILQ_FOREACH(vent, &var_head, link) {
522 		v = vent->var;
523 		if (v->flag & DSIZ) {
524 			vent->dwidth = vent->width;
525 			vent->width = 0;
526 		}
527 		if (v->flag & USER)
528 			needuser = 1;
529 		if (v->flag & COMM)
530 			needcomm = 1;
531 	}
532 }
533 
534 static void
535 dynsizevars(KINFO *ki)
536 {
537 	struct varent *vent;
538 	const VAR *v;
539 	int i;
540 
541 	STAILQ_FOREACH(vent, &var_head, link) {
542 		v = vent->var;
543 		if (!(v->flag & DSIZ))
544 			continue;
545 		i = (v->sproc)( ki);
546 		if (vent->width < i)
547 			vent->width = i;
548 		if (vent->width > vent->dwidth)
549 			vent->width = vent->dwidth;
550 	}
551 }
552 
553 static void
554 sizevars(void)
555 {
556 	struct varent *vent;
557 	int i;
558 
559 	STAILQ_FOREACH(vent, &var_head, link) {
560 		i = strlen(vent->header);
561 		if (vent->width < i)
562 			vent->width = i;
563 		totwidth += vent->width + 1;	/* +1 for space */
564 	}
565 	totwidth--;
566 }
567 
568 static const char *
569 getfmt(char **(*fn) (kvm_t *, const struct kinfo_proc *, int), KINFO *ki, char
570     *comm, int maxlen)
571 {
572 	const char *s;
573 
574 	if ((s =
575 	    fmt_argv((*fn)(kd, ki->ki_proc, termwidth), comm, maxlen)) == NULL)
576 		err(1, NULL);
577 	return (s);
578 }
579 
580 static void
581 saveuser(KINFO *ki)
582 {
583 	/*
584 	 * save arguments if needed
585 	 */
586 	if (needcomm) {
587 		ki->ki_args = getfmt(kvm_getargv, ki, KI_PROC(ki, comm),
588 		    MAXCOMLEN);
589 	} else {
590 		ki->ki_args = NULL;
591 	}
592 	if (needenv) {
593 		ki->ki_env = getfmt(kvm_getenvv, ki, NULL, 0);
594 	} else {
595 		ki->ki_env = NULL;
596 	}
597 }
598 
599 static int
600 pscomp(const void *arg_a, const void *arg_b)
601 {
602 	const KINFO *a = *(KINFO * const *)arg_a;
603 	const KINFO *b = *(KINFO * const *)arg_b;
604 	double di;
605 	segsz_t si;
606 	int i;
607 
608 #define VSIZE(k) (KI_PROC(k, vm_dsize) + KI_PROC(k, vm_ssize) + \
609 		  KI_PROC(k, vm_tsize))
610 
611 #if 0
612 	if (sortby == SORTIAC)
613 		return (KI_PROC(a)->p_usdata.bsd4.interactive - KI_PROC(b)->p_usdata.bsd4.interactive);
614 #endif
615 	if (sortby == SORTCPU) {
616 		di = getpcpu(b) - getpcpu(a);
617 		if (di < 0.0)
618 			return(-1);
619 		if (di > 0.0)
620 			return(+1);
621 		/* fall through */
622 	}
623 	if (sortby == SORTMEM) {
624 		si = VSIZE(b) - VSIZE(a);
625 		if (si < 0)
626 			return(-1);
627 		if (si > 0)
628 			return(+1);
629 		/* fall through */
630 	}
631 	i = KI_PROC(a, tdev) - KI_PROC(b, tdev);
632 	if (i == 0)
633 		i = KI_PROC(a, pid) - KI_PROC(b, pid);
634 	return (i);
635 }
636 
637 /*
638  * Chain (-R) option.  Sub-sorts by parent/child association.
639  */
640 static int dochain_final(KINFO **kfinal, KINFO *base, int j);
641 
642 static void
643 dochain (KINFO **ksort, int nentries)
644 {
645 	int i;
646 	int j;
647 	int hi;
648 	pid_t ppid;
649 	KINFO *scan;
650 	KINFO **khash;
651 	KINFO **kfinal;
652 
653 	/*
654 	 * First hash all the pids so we can quickly locate the
655 	 * parent pids.
656 	 */
657 	khash = calloc(KHSIZE, sizeof(KINFO *));
658 	kfinal = calloc(nentries, sizeof(KINFO *));
659 
660 	for (i = 0; i < nentries; ++i) {
661 		hi = KI_PROC(ksort[i], pid) & KHMASK;
662 
663 		ksort[i]->ki_hnext = khash[hi];
664 		khash[hi] = ksort[i];
665 	}
666 
667 	/*
668 	 * Now run through the list and create the parent associations.
669 	 */
670 	for (i = 0; i < nentries; ++i) {
671 		ppid = KI_PROC(ksort[i], ppid);
672 
673 		if (ppid <= 0 || KI_PROC(ksort[i], pid) <= 0) {
674 			scan = NULL;
675 		} else {
676 			for (scan = khash[ppid & KHMASK];
677 			     scan;
678 			     scan = scan->ki_hnext) {
679 				if (ppid == KI_PROC(scan, pid))
680 					break;
681 			}
682 		}
683 		if (scan) {
684 			ksort[i]->ki_parent = scan;
685 			*scan->ki_ctailp = ksort[i];
686 			scan->ki_ctailp = &ksort[i]->ki_cnext;
687 		}
688 	}
689 
690 	/*
691 	 * Now regenerate the list starting at root entries, then copyback.
692 	 */
693 	for (i = j = 0; i < nentries; ++i) {
694 		if (ksort[i]->ki_parent == NULL) {
695 			ksort[i]->ki_indent = 0;
696 			j = dochain_final(kfinal, ksort[i], j);
697 		}
698 	}
699 	if (i != j)
700 		errx(1, "dochain failed");
701 
702 	bcopy(kfinal, ksort, nentries * sizeof(kfinal[0]));
703 	free(kfinal);
704 	free(khash);
705 }
706 
707 static int
708 dochain_final(KINFO **kfinal, KINFO *base, int j)
709 {
710 	KINFO *scan;
711 
712 	kfinal[j++] = base;
713 	for (scan = base->ki_cbase; scan; scan = scan->ki_cnext) {
714 		/*
715 		 * Don't let us loop
716 		 */
717 		if (scan->ki_indent >= 0)
718 			continue;
719 		scan->ki_indent = base->ki_indent + 1;
720 		j = dochain_final(kfinal, scan, j);
721 	}
722 	return (j);
723 }
724 
725 /*
726  * ICK (all for getopt), would rather hide the ugliness
727  * here than taint the main code.
728  *
729  *  ps foo -> ps -foo
730  *  ps 34 -> ps -p34
731  *
732  * The old convention that 't' with no trailing tty arg means the users
733  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
734  * feature is available with the option 'T', which takes no argument.
735  */
736 static char *
737 kludge_oldps_options(char *s)
738 {
739 	size_t len;
740 	char *newopts, *ns, *cp;
741 
742 	len = strlen(s);
743 	if ((newopts = ns = malloc(len + 2)) == NULL)
744 		err(1, NULL);
745 	/*
746 	 * options begin with '-'
747 	 */
748 	if (*s != '-')
749 		*ns++ = '-';	/* add option flag */
750 	/*
751 	 * gaze to end of argv[1]
752 	 */
753 	cp = s + len - 1;
754 	/*
755 	 * if last letter is a 't' flag with no argument (in the context
756 	 * of the oldps options -- option string NOT starting with a '-' --
757 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
758 	 *
759 	 * However, if a flag accepting a string argument is found in the
760 	 * option string, the remainder of the string is the argument to
761 	 * that flag; do not modify that argument.
762 	 */
763 	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
764 		*cp = 'T';
765 	else {
766 		/*
767 		 * otherwise check for trailing number, which *may* be a
768 		 * pid.
769 		 */
770 		while (cp >= s && isdigit(*cp))
771 			--cp;
772 	}
773 	cp++;
774 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
775 	ns += cp - s;
776 	/*
777 	 * if there's a trailing number, and not a preceding 'p' (pid) or
778 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
779 	 */
780 	if (isdigit(*cp) &&
781 	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
782 	    (cp - 1 == s || cp[-2] != 't'))
783 		*ns++ = 'p';
784 	strcpy(ns, cp);		/* and append the number */
785 
786 	return (newopts);
787 }
788 
789 static int
790 check_procfs(void)
791 {
792 	struct statfs mnt;
793 
794 	if (statfs("/proc", &mnt) < 0)
795 		return (0);
796 	if (strcmp(mnt.f_fstypename, "procfs") != 0)
797 		return (0);
798 	return (1);
799 }
800 
801 static void
802 usage(void)
803 {
804 
805 	fprintf(stderr, "%s\n%s\n%s\n",
806 	    "usage: ps [-aCcefhHjlmrSTuvwx] [-M core] [-N system] [-O fmt] [-o fmt] [-p pid]",
807 	    "          [-t tty] [-U username]",
808 	    "       ps [-L]");
809 	exit(1);
810 }
811